Why can only „real“ dog bark?
Hello,
consider this code:
class Animal{
void play(){System.out.println("Animal.play()"); };
void move(){System.out.println("Animal.move()"); };
}
class Dog extends Animal{
//overriding in play / move method
void play(){System.out.println("Dog.play()");};
void move(){System.out.println("Dog.move()");};
void bark(){System.out.println("Dog.bark()");};
}
public class TestPolymorphismOverriden1{
public static void main(
String args[ ]){
//(Late)Binding because the right object(Dog) will be assigned at run time. to the Animal reference "d".
Dog d = new Dog();
d.play();
d.move();
d.bark();
}
}
C:\Java\EigeneJavaProgramme>javac TestPolymorphismOverriden.java
TestPolymorphismOverriden.java:17: cannot resolve symbol
symbol : method bark ()
location: class Animal
d.bark();
^
1 error
In this case a Dog object is referred to by an Animal reference.
What does this mean when I invoke a Dog method with this Dog object with Animal reference?
It means that according to late binding (
Polymorphism) JVM recognizes that d is a Dog object and calls
the play-method of Dog. So d.play whould lead to output: „Dog.play“.
what I don’t understand is when d is a Dog object why can’t I call d.bark which is not an overriden method
from animal But an Dog specific method.
In the example as follows I create a „real“ Dog object (Dog reference and Dog object) and this dog can
Bark wheras a Dog Object with an Animal reference cannot bark?
class Animal{
void play(){System.out.println("Animal.play()"); };
void move(){System.out.println("Animal.move()"); };
}
class Dog extends Animal{
//overriding in play / move method
void play(){System.out.println("Dog.play()");};
void move(){System.out.println("Dog.move()");};
void bark(){System.out.println("Dog.bark()");};
}
public class TestPolymorphismOverriden{
public static void main(String args[]){
//(Late)Binding because the right object(Dog) will be assigned at run time. to the Animal reference "d".
Animal d = new Dog();
d.play();
d.move();
Dog d1 = new Dog();
d1.bark();
}
}
C:\Java\EigeneJavaProgramme>
java TestPolymorphismOverriden1
Dog.play()
Dog.move()
Dog.bark()