class Animal {
void stinky(){
System.out.println("stinky animal !");
}
}
class Dog extends Animal{
public void stinky() {
System.out.println("stinky dog !");
}
}
class Cow extends Animal{
public void stinky() {
System.out.println("stinky cow !");
}
"History would be kind to me, for I intend to write it."
lucas van derstappen wrote:I am reading now a SCJP5 study guide book (Osborne, 2006 - Sierra,Bates) and i am little confused.
Problem is in these two sentences : ( two minute drill chapter 2, pages 153,154)
Chapter about Polymorphism :
(I.) Reference variable`s type (not the object`s type) determines which methods can be called.
And
Chapter about overriding :
(II.) Object type (not reference variable`s type), determines which overriden method is used at runtime.
Just imagine :
class Animal {
void stinky(){
System.out.println("stinky animal !");
}
}
class Dog extends Animal{
public void stinky() {
System.out.println("stinky dog !");
}
}
class Cow extends Animal{
public void stinky() {
System.out.println("stinky cow !");
}
now :
Animal a = new Dog();
a.stinky();
according first sentence should be printed : 'stinky animal !'
according second sentence should be printed -> 'stinky dog !' (this is printed in reality)
Is explanation in that book wrong or i made logical mistake somewhere ?
(sorry for my english)
Thanks
"History would be kind to me, for I intend to write it."
Priyam Srivastava wrote:No you wont be able to even compile in that case.
Beacuse at compile time the comiler sees that the class type of obj is Animal and there exist no method bark() in Animal class. Hence it will display a compile time error.
"History would be kind to me, for I intend to write it."
lucas van derstappen wrote:
Chapter about Polymorphism :
(I.) Reference variable`s type (not the object`s type) determines which methods can be called.
And
Chapter about overriding :
(II.) Object type (not reference variable`s type), determines which overriden method is used at runtime.
be a well encapsulated person, don't expose your privates, unless you public void getWife()!