For starters, rules are simple. Can the child exist before the parent? No. That is why we always call super()
when creating a subclass. In that way, every member of the superclass gets "copied" to the subclass.
So I will give example:
class Duck extends Animal {
int size;
public Duck(int size) {
super();
this.size = size;
}
}
My question is why can't we call Animal constructor with Animal()
and not super()
. Or, why can't we do this:
class Duck extends Animal {
int size;
public Duck(int size) {
Animal();
this.size = size;
}
}
Shouldn't both codes compile? I mean there is technically no difference between them and the compiler can pretty much know that Duck
IS-A Animal
by the keyword extends. So what is the problem then?
A good programming language is one that lets the author be expressive about their intent with as few syntactical variations as possible in which to achieve that. The more variations there are, the more rules a programmer has to carry around in their head, and the more complex a compiler has to be to support all those variations.
Suppose I eschew Java naming conventions and use a capital letter in the name of a static method:
class Duck extends Animal {
int size;
public Duck(int size) {
Animal(); //super or static method?
this.size = size;
}
private static void Animal() {
System.out.println("I'm a static method");
}
}
Is the Duck constructor calling the Animal constructor or the static method? We could introduce a new rule which covers this case but it would be introducing more complexity.
What you are suggesting is two ways to achieve exactly the same thing. There is no reason to support that when super
fulfills that purpose perfectly well on its own.
Why don't they also allow us to use parent()
or superconstructor()
or superclass()
? The onus is on you to provide a compelling reason why it should be supported.