Hello everyone. I have created a class in Java named Farm which contains a list of animals(cow,pig and chick).
myFarm is an array of object of Farm class containing objects of NamedCow,pig and chick class.

I have not understand one line in my code: NamedCow named = (NamedCow)myFarm.get(0);
here what is the meaning of the NamedCow enclosed within parentheses in the right side. Cn anyone please tell me??

Edited 2 Years Ago by SK33

you wrote the class, yet you don't understand what you wrote? then how exactly did you write it, or how, for that matter?

myFarm is an array of object of Farm class ...

makes very little (if any) sense to me, and it doesn't seem to be so by your next explanation.

it looks like myFarm is a list created with a more 'generic' type:

List<Animal> animals = createAnimalList();

now, it is possible that each animal in that list is a cat, and thus should be able to execute the method 'sayMeow()' which is declared within the class Cat, but not within the class Animal (since not all animals say 'meow')

so, you'll need an instance of Cat to call that method.
You can't just do:

Cat myCat = animals.get(0);

because, even though it is a cat you added, the list is declared as a list of Animals, and could just as well be a Dog.

so, you'll need to cast that element to a Cat:

Cat myCat = (Cat)animals.get(0);

That is called "Cast". I will try to explain you. If you have array of class Object. Object class is parent class of every class in Java, so in that array you can put whatever you want...
So if you have on like this:
arrayOfObject[0] = 150; // int
arrayOfObject[1] = "Hello"; // String
arrayOfObject[2] = 1.441; // double
NamedCow n = new NamedCow();
arrayOfObject[3] = n;

And if you know what is in array you need to "Cast".
double newDouble = arrayOfObject[2];
but what will happen if you try this:
String newString = arrayOfObject[2];
You want String but array contains double. So he will ask you to cast it.
You can get to problem if you try to cast double into NamedCow:
NamedCow newNamedCow = arrayOfObject[2];
He will throw exception... So you need to know what is in array and cast it...

however, 1.441 will AFAIK box to a Float, not a Double.
150 might box to a Byte.
This is of course a specific problem here because of the use of hardcoded magic numbers rather than fields, and not having those magic numbers forced to a specific type.
Forcing double through 1.441d and int through 150i would prevent any such issues.

Answers, as always in the JLS...
but in short:
integer literals are always treated as int unless they have a "l" at the end (JLS 3.10.1).
f.p. literals are always treated as double unless the have an "f" at the end (JLS 3.10.2).
ints always box to Integer, doubles to Doubles (JLS 5.1.7)

Edited 2 Years Ago by JamesCherrill

This article has been dead for over six months. Start a new discussion instead.