instances

in the below code is it correct that myAnimal is an instance of the Animal class?

Animal myAnimal = myCat;

class Animal{

staticvoid testClassMethod(){

System.out.println("The class method in Animal.");

}

void testInstanceMethod(){

System.out.println("The instance method in Animal.");

}

}

class Catextends Animal{

staticvoid testClassMethod(){

System.out.println("The class method in Cat.");

}

void testInstanceMethod(){

System.out.println("The instance method in Cat.");

}

publicstaticvoid main(String[] args){

Cat myCat =new Cat();

Animal myAnimal = myCat;

Animal.testClassMethod();

myAnimal.testInstanceMethod();

}

}

[1670 byte] By [mark_8206a] at [2007-11-27 10:31:19]
# 1

Sort-of. It's an instance of Cat, but through the wonders of inheritance, it's also an instance of Animal. But (as I suspect you think, but may be wrong) it's not an Animal just because you assigned it to an Animal reference

georgemca at 2007-7-28 18:08:44 > top of Java-index,Java Essentials,New To Java...
# 2

you're right!, it's also an instance of Animal

leonardoauera at 2007-7-28 18:08:44 > top of Java-index,Java Essentials,New To Java...
# 3

I thought Cat was an instance of a Pet. But perhaps I'm just confusing the issue.

George123a at 2007-7-28 18:08:44 > top of Java-index,Java Essentials,New To Java...
# 4

I would think Pet would be an interface, implemented by some animal classes. Or is it dynamic?

BigDaddyLoveHandlesa at 2007-7-28 18:08:44 > top of Java-index,Java Essentials,New To Java...
# 5

Could anyone please give me a brief explanation of what's happening in those cat and animal classes, how does the method in the superclass get overridden? myAnimal is an instance of both classes?

thanks

mark_8206a at 2007-7-28 18:08:44 > top of Java-index,Java Essentials,New To Java...
# 6

An object is an instance of exactly one class (operator instanceof not withstanding), but an object can have many types.

Animal sparklePrincess = new Cat();

sparklePrincess references to an object that has three types: Cat, Animal and Object.

BigDaddyLoveHandlesa at 2007-7-28 18:08:44 > top of Java-index,Java Essentials,New To Java...
# 7

myAnimal is an instance of Cat class. Cat class inherits from Animal class (neither is instansiated). I suggest reading up on inheritance rather than trying to exaplain where overridden functions come into all this here.

George123a at 2007-7-28 18:08:44 > top of Java-index,Java Essentials,New To Java...