When you declare something in this way:
ParentClass variable = new ChildClass(Args);
The methods and fields in ParentClass
are the only ones available to you. It is restricted because you declared the type as a ParentClass
. Because Car
's volume is 1600 and the object is restricted to the ParentClass
's methods and fields, it prints 1600.
An example would be as follows:
Consider I had an Apple Class and a Fruit class:
public class Fruit {
private String type;
public Fruit(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
And the Apple Class:
public class Apple extends Fruit {
private String variant;
public Apple(String variant) {
System.out.println("I like " + variant + apples too!");
super("Apple");
}
public String getVariant() {
return variant;
}
}
And now I instantiate like this:
Fruit ap = new Apple("Fiji");
I don't have access to getVariant()
or any methods in the Apple class because the type is of the parent class, not of Apple. I would be able to do getType()
but that's it.
In your case:
public class SportsCar extends Car {
public int volume;
SportsCar() {
this(3000);
}
SportsCar(int volume) {
this.volume = volume;
}
public String toString() {
return "SportsCar:"+volume;
}
}
Although SportsCar
has it's own constructor and takes it's own volume, the parent class Car
is the actual type, causing the Car
constructor to be called, hence setting volume
to 1600. To specify a SportsCar
object, do this:
SportsCar sc = new SportsCar(3500);
System.out.print(sc.toString());
This will print out:
SportsCar:3500
You can also typecast it like so:
Car c = new SportsCar(1600);
System.out.print(((SportsCar) c).toString());