Reputation: 97
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);
}
}
Upvotes: 0
Views: 70
Reputation: 7032
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.
Upvotes: 3
Reputation: 10540
The Java compiler will automatically insert a call to super()
in this case. I'd suggest reading over this Java tutorial, specifically this part:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
Upvotes: 1
Reputation: 1289
If you do not include a call to the parents constructor then the parents( no arg ) constructor will get called before the first line of execution in the current class
Upvotes: 0