in polymorphism, consider dog class extends from animal class
Animal a= new Dog();
and when a.play() is called, whether it will call animal class mehod or dog's method? it depends on reference variable type?
grigoris philippoussis
Greenhorn
Joined: Oct 22, 2007
Posts: 16
posted
0
if you've overridden play() in Dog, it will call that. otherwise it will call the base class method. the compiler looks at the reference type, at run-time, it looks at the object.
With animal reference to dog you can only call methods which are defined in animal class only, you can not call dog's methods with animal reference to dog. You can call dogs methods with dog reference I mean
the play() method must be defined in animal, otherwise if it were in dog class you cannot say
animalReferencetoDog.play() <----it must be defined in animal class
[ October 24, 2008: Message edited by: Anut Walidera ]
Remember that play must be a instance method. If it is static you will call play in Animal:
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
krishna pr
Greenhorn
Joined: Oct 28, 2008
Posts: 8
posted
0
Ciao Anut,
With animal reference to dog you can only call methods which are defined in animal class only, you can not call dog's methods with animal reference to dog.
I agree with you, but what if the method is overridden in the Dog class, Can't the animal reference be used then to call the overridden method in the Dog class.
But why not write a program yourself to find out? It's easier, faster and you learn much more from it.
Jimmy Clark
Ranch Hand
Joined: Apr 16, 2008
Posts: 2187
posted
0
With animal reference to dog you can only call methods which are defined in animal class only, you can not call dog's methods with animal reference to dog.
I agree with you, but what if the method is overridden in the Dog class, Can't the animal reference be used then to call the overridden method in the Dog class.
If the method is overriden in the Dog class, that implies that the method is declared in the Animal class. Or else you would not be overriding the method. Yes, the Animal reference can be used to call the overridden method in the Dog class. The Animal reference cannot be used to call a method that is only declared and implemented in the Dog class.
With an Animal reference, you can only call methods that are declared in the Animal class. To understand this better, if the Dog class has any methods that are not declared in the Animal class, you will not be able to call these methods with an Animal reference, even if the actual object is an instance of Dog. [ October 28, 2008: Message edited by: James Clark ]
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.