I struggle to observe the difference of creating objects with reference to the parent class data type or child class data type (as custom to polymorphism)
Creating two objects without referencing derived class as the data type:
class Main {
public static void main(String[] args) {
spaceship Spaceship1 = new spaceship(34.6, "Apollo 11", 1600);
car Car1 = new car(100.1, "Tesla", "OPEN");
Spaceship1.go();
Car1.go();
}
}
class Vehicle{
protected double speed;
protected String name;
public Vehicle(double speed, String name){
this.speed = speed;
this.name = name;
}
public void go(){}
}
class spaceship extends Vehicle{
private int altitude;
public spaceship(double speed, String name, int altitude){
super(speed, name);
this.altitude = altitude;
}
public void go(){
System.out.println(this.name + " is going at the speed of " + this.speed +" at the altitude of " + this.altitude);
}
}
class car extends Vehicle{
private String window;
public car(double speed, String name, String window) {
super(speed, name);
this.window = window;
}
public void go(){
System.out.println(this.name + " is going at the speed of " + this.speed + " with its windows " + this.window);
}
}
Creating two objects referencing derived class as the data type:
class Main {
public static void main(String[] args) {
Vehicle Spaceship1 = new spaceship(34.6, "Apollo 11", 1600);
Vehicle Car1 = new car(100.1, "Tesla", "OPEN");
Spaceship1.go();
Car1.go();
}
}
class Vehicle{
protected double speed;
protected String name;
public Vehicle(double speed, String name){
this.speed = speed;
this.name = name;
}
public void go(){}
}
class spaceship extends Vehicle{
private int altitude;
public spaceship(double speed, String name, int altitude){
super(speed, name);
this.altitude = altitude;
}
public void go(){
System.out.println(this.name + " is going at the speed of " + this.speed +" at the altitude of " + this.altitude);
}
}
class car extends Vehicle{
private String window;
public car(double speed, String name, String window) {
super(speed, name);
this.window = window;
}
public void go(){
System.out.println(this.name + " is going at the speed of " + this.speed + " with its windows " + this.window);
}
}
Is the difference only intended to be on a syntax level or are there some practical differences?