I'm trying to learn the concept of super
. Could someone please tell me what the i
in super(i)
is referring to?
Is it the private int
variable i
in the NaturalNumber
class? Is it the parameter in the NaturalNumber?
Is it referring to something else? I'm very confused by the syntax.
class NaturalNumber {
private int i;
public NaturalNumber(int i) { this.i = i; }
// ...
}
class EvenNumber extends NaturalNumber {
public EvenNumber(int i) { super(i); }
// ...
}
super(arguemnts)
is call to superclass constructor to which you pass arguments
.
In case of class EvenNumber extends NaturalNumber
it is mechanism which ensures NaturalNumberness of your class.
What happens in this case is that you are passing to super
class constructor same value you passed to EvenNumber
class via public EvenNumber(int i)
. So it will initialize private int i
field (which you don't have direct access to from EvenNumber
since it is private).
Maybe you will better see it if we rename variables a little:
class NaturalNumber {
private int value;
public NaturalNumber(int naturalValue) {
this.value = naturalValue;
}
// ...
}
class EvenNumber extends NaturalNumber {
public EvenNumber(int oddValue) {
super(oddValue);
}
// ...
}
So when you create instance of EvenNumber
via new EvenNumber(2)
first thing which happens in EvenNumber(int oddValue)
constructor is super(2)
which will invoke NaturalNumber(int naturalValue)
constructor and pass 2
to it, which finally will set int value
to 2
.