This question has been bugging me for a while now, and I haven’t found a good answer (other than “that’s just how it is”).
Let me give some background code, to show what I’m talking about.
class Note {
private final String name = "Note";
public Note() {
System.out.println(name);
}
// ...
}
class Todo extends Note {
private final String name = "Todo";
public Todo() {
System.out.println(name);
}
// ...
}
// ...
Note note = new Todo(); // case 1
Todo todo = new Todo(); // case 2
So how come both case 1 and case 2 print out:
Note
Todo
This makes no sense, since Todo() (constructor) does not call super() (at least not visibly). Why would the sub-class have to call the parents default constructor, why not just require any sub-class to implement a constructor?
I read a couple questions related to this, but none answer why.
Edit:
I guess my example was kind of poor, but It’s actually a derivative from a Java 7 Certification question.. From the collective of answers I now understand why. Let me provide a better example:
public Note {
private String description;
public Note() {
description = "I'm a Note";
}
public Note( String description ) {
this.description = description;
}
// getters/setters/etc.
}
public Todo extends Note {
// field vars..
public Todo() {
// empty constructor
}
// getters/setters/etc..
}
So now this makes more sense, since when Todo is created, if super() was not inserted behind the covers, the Note aspect of the Todo would not be initialized. Which would be pointless to have a sub-class in that case. Thanks all!
The question can be separated into two parts.
privatefields), this can only be dealt with by calling a constructor of the superclass.super()explicitly? This is just a fairly arbitrary design decision made in Java to make code look simpler. It ties in nicely with the concept of adefault constructor(i.e. the implied no-arg constructor that exists in classes that don’t have an explicit constructor defined), although as can be seen in your example, it also works when you have a no-arg constructor explicitly defined in the superclass.