the following code i have inherited subclass from super class and i have initialized same attribute with same types and access modifiers in the sub class also. but the output shows 0 for i already initialized values attributes. i want to know the exact reason for that.
class Super {
int a = 10;
private int b = 30;
final int c = 30;
static int d = 40;
final static int e = 50;
void printValues() {
System.out.print("Super : ");
System.out.println(+a + " " + b + " " + c + " " + d + " " + e);
}
Super() {
printValues();
}
}
class Sub extends Super {
int a = 100;
private int b = 300;
final int c = 300;
static int d = 400;
final static int e = 500;
void printValues() {
System.out.print("Sub : ");
System.out.println(+a + " " + b + " " + c + " " + d + " " + e);
}
}
class TwentyFIve {
public static void main(String args[]) {
new Sub();
}
}
i expected the result for the above code as follows; Sub : 100 300 300 400 500 but i got the output as follows; Sub : 0 0 300 400 500
The problem is that you are already printing the values before your object has been completely constructed (as pointed out in a comment from @tgdavies). When single-stepping through your program (your IDE can do that), you'll see that the
printValues()is done before theSubclass has a chance to initialize its fields.As a rule of thumb, avoid "doing" anything inside a constructor. Especially, in a constructor don't call a method that can be overridden by some subclass, as this method will see a partially-empty instance.
Remove the
printValues();call from theSuper()constructor and place it into yourmain()method likeThen, you'll see the fully-initialized state of your instance.
By the way, for educational purposes it's good to sometimes break the best-practices rules (having fields with the same name in superclass and subclass), just to see how much confusion arises from that. The learning effect should be not to do that in production code.
And by the way, you should delete the superfluous
+at the beginning of+a + " " + b + " " + c + " " + d + " " + e.