I came across this code while looking for exam prep questions. I don't understand what is invoking the superclass constructor in this code?
The output is ---> feline cougar cc
THL
public class Feline{
public String type = "f ";
public Feline(){
System.out.print("feline ");
}
}
-
public class Cougar extends Feline {
public Cougar(){
System.out.print("cougar ");
}
public static void main(String[] args){
new Cougar().go();
}
void go(){
type = "c ";
System.out.print(this.type + super.type);
}
}
When you have a class that extends some other class, eg Cougar extends Feline
, there must be a call to the super class at the top of the constructor. When you don't write one, Java assumes you meant to call the default super class constructor. So your constructor:
public Cougar(){
System.out.print("cougar ");
}
Is actually interpreted as:
public Cougar(){
super();
System.out.print("cougar ");
}
Hence the call to the super class constructor. It's interesting to note that because all classes are extensions of the class Object
, there is a call to a super class constructor at the beginning of every constructor that you'll ever write - either an explicit one you've included with or without arguments, or the default super class constructor if you do not specify.