class AA{
int x;
protected AA(){init (1008);}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
I know that this code will print 2019. Yet I do not understand why the superclass constructor,when called, will use the init method from de subclass instead the one from the superclass.
Yet I do not understand why the superclass constructor,when called, will use the init method from de subclass instead the one from the superclass.
Because that's the one associated with the object being constructed. this
within the superclass constructor is a reference to the subclass object being constructed, so just like any other call to init
using that reference, it uses the subclass's init
.
This may help, note the lines with comments on the end — the comments say what those lines output:
class AA{
int x;
protected AA() {
System.out.println(this.getClass().getName()); // "BB"
System.out.println(this instanceof BB); // true
init(1008);
}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
It's because subclasses can override methods that calling non- final
, non- private
methods from a constructor is usually best avoided.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.