Let's say I have the following classes:
public abstract class Animal {
public abstract void talk();
}
class Dog extends Animal {
@Override
public void talk() {
System.out.println("Woof");
}
}
class Cat extends Animal {
@Override
public void talk() {
System.out.println("Meow");
}
}
Now I create a new class for testing and I want a method that will call the corresponding talk() method for the type of animal passed as its parameter. Then I call the method on objects dog and cat.
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
Test t = new Test();
t.makeAnimalTalk(dog);
t.makeAnimalTalk(cat);
}
public void makeAnimalTalk(Animal animal) {
animal.talk();
}
}
And this works. But what's bothering me is this:
public void makeAnimalTalk(Animal animal) {
animal.talk();
}
The parameter being passed here is of class type Animal, which is an abstract class. I know very well that we cannot make objects of an abstract class, so what is animal? How does this work? The program works even if I do something like this:
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
I'm coming from C++ and as far as I know this wouldn't work written in the language.
Dogis also an instance of classAnimal.makeAnimalTalkwould bevoid makeAnimalTalk(Animal& animal)and Java'sAnimal dog = new Dog();would beAnimal& dog = new Dog();Animal dog = new Dog()(and use all members ofAnimalon thedoginstance - like thetalk()method) -- BTW sinceAnimalimplicitly extendsObject,Object dog = new Dog()is also valid (but sincetalk()is not a member ofObject,dog.talk()will not work)