A
ankur
I was little confused as to how the this reference works in this case.
I thought that the this reference in SuperClassA constructor would
call the doValue() in superclass A.
package pack4;
class SuperclassA {
protected int superValue; // (1)
SuperclassA() { // (2)
System.out.println("Constructor in SuperclassA");
this.doValue(); // (3)
}
void doValue() { // (4)
this.superValue = 911;
System.out.println("superValue: " + this.superValue);
}
}
class SubclassB extends SuperclassA {
private int value = 800; // (5)
SubclassB() { // (6)
super();
System.out.println("Constructor in SubclassB");
this.doValue();
System.out.println("superValue: " + this.superValue);
}
void doValue() { // (7)
System.out.println("value: " + this.value);
}
}
public class ObjectInitialization {
public static void main(String[] args) {
System.out.println("Creating an object of SubclassB.");
new SubclassB(); // (8)
}
}
Output :
Creating an object of SubclassB.
Constructor in SuperclassA
value: 0
Constructor in SubclassB
value: 800
superValue: 0
Thanks,
Ankur
I thought that the this reference in SuperClassA constructor would
call the doValue() in superclass A.
package pack4;
class SuperclassA {
protected int superValue; // (1)
SuperclassA() { // (2)
System.out.println("Constructor in SuperclassA");
this.doValue(); // (3)
}
void doValue() { // (4)
this.superValue = 911;
System.out.println("superValue: " + this.superValue);
}
}
class SubclassB extends SuperclassA {
private int value = 800; // (5)
SubclassB() { // (6)
super();
System.out.println("Constructor in SubclassB");
this.doValue();
System.out.println("superValue: " + this.superValue);
}
void doValue() { // (7)
System.out.println("value: " + this.value);
}
}
public class ObjectInitialization {
public static void main(String[] args) {
System.out.println("Creating an object of SubclassB.");
new SubclassB(); // (8)
}
}
Output :
Creating an object of SubclassB.
Constructor in SuperclassA
value: 0
Constructor in SubclassB
value: 800
superValue: 0
Thanks,
Ankur