more silly questions that are probably elementary to most but.....
- From: John T <printdude1968@xxxxxxxxx>
- Date: Tue, 13 Feb 2007 00:30:14 GMT
Here's a class...pretty classy eh?
package chapter08;
import java.util.ArrayList;
public class AnimalTester {
public static void main(String [] args) {
Wolf aWolf = new Wolf();
Animal aHippo = new Hippo();
ArrayList<Object> myList = new ArrayList<Object>();
myList.add(aWolf);
myList.add(aHippo);
Cat c = new Cat();
myList.add(c);
for (Object o : myList) {
System.out.println(o.getClass());
}
}
}
I have an Animal class, Feline, Canine, Hippo and Cat, Wolf, Dog... well you can guess the rest.
If I run this program I get this:
class chapter08.Wolf
class chapter08.Hippo
class chapter08.Cat
Which is what I expected..sort of... But my question is, if getClass() tells me exactly what class the object is when I added it to the ArrayList why can't I access the instance variables of Wolf, Hippo and Cat once the object is extracted. Based on what I see from code completion, the only instance variables and methods I have access to are the ones that are inherited from the class Object...but if I have a Cat class
package chapter08;
public class Cat extends Feline {
void makeNoise() {
}
void eat(){
}
@Override
public void roam() {
// TODO Auto-generated method stub
}
}
why can't I say o.eat() or o.makeNoise()
It seems to me that the JVM knows what the class of the object is when I extract it from the ArrayList so why can't I get at the instance variables (is there a shorter way to say this?) and the methods. I know I can't, but I would like to know why... a short, one or two sentences would be splendid.
Thanks...
.
- Follow-Ups:
- Prev by Date: for ferdinanda: genuinely peaceful postings - ur - (1/1)
- Next by Date: Re: more silly questions that are probably elementary to most but.....
- Previous by thread: for ferdinanda: genuinely peaceful postings - ur - (1/1)
- Next by thread: Re: more silly questions that are probably elementary to most but.....
- Index(es):
Relevant Pages
|