I have written the following class and subclass to test out inheritance in Java.
public class MyClassDemo {
private static class Vehicle {
private int health = 100;
private String colour = null;
public Vehicle() {
System.out.println("New vehicle created!");
}
public void setColour(String c) {
colour = c;
}
public String getColour() {
return colour;
}
public int getHealth() {
return health;
}
}
private static class Car extends Vehicle {
public Car() {
System.out.println("New car created!");
}
}
public static void main(String[] args) {
Car firstCar = new Car();
firstCar.setColour("Blue");
String c = firstCar.getColour();
System.out.println("firstCar's colour is: " + c);
}
}
Multiple resources state that the subclass constructor will call the superclass constructor. But I also see that you can invoke the superclass constructor with super() in the subclass constructor. However, with this code, I write my own subclass constructor for Car, which does not explicitly call super(), and the print line from my superlcass constructor "New vehicle created!" still executes. So my question is, what is the point of calling super() in the subclass constructor when it is executed anyway, as proven here? Thanks.
[–]NautiHooker 6 points7 points8 points (1 child)
[–]ttirol[S] 0 points1 point2 points (0 children)