I don't understand what's the use of referencing a superclass to a reference of a subclass. From most materials that I've read online. The main point they highlight is that with dynamic binding, the overriden method gets called rather than the superclass method. But this is true with normal instantiation as well. Suppose the following code
package rmit.cosc2081.Test;
class Animal {
protected String species;
protected int population;
void reproduce() {
population += 1;
}
public int getPopulation() {
return population;
}
}
class Frog extends Animal{
@Override
void reproduce() {
population += 10;
}
}
public class Main {
public static void main(String[] args) {
//Normal Polymorphism
Frog goldenPoisonFrog = new Frog();
goldenPoisonFrog.reproduce();
System.out.println(goldenPoisonFrog.getPopulation());
//Dynamic Polymorphism
Animal toad = new Frog();
toad.reproduce();
System.out.println(toad.getPopulation());
}
}
The method goldenPoisonFrog.reproduce() and toad.reproduc() both invoke the overriden method.
I think what I'm really asking here is what is the difference between this code:
Frog goldenPoisonFrog = new Frog()
... and this code
Animal goldenPoisonFrog = new Frog()
Like what is the difference between these two and when would I use one and the other?