Java - extends why super variable a is 0

Take a look at this code:

class Sup { int a = 8; public void printA() { System.out.println(a); } Sup() { printA(); } } public class Sub extends Sup { int a = 9; @Override public void printA() { System.out.println(a); } Sub() { printA(); } public static void main(String[] args) { Sub sub = new Sub(); } } 

Result: console printing: 0 9
I know that a subclass will call the constructor superclass first
but why? 0 9 , not 8 9 ?

+8
java extend
source share
1 answer

When the Sup constructor calls printA() , it executes the printA method (which overrides the method with the same Sup class name), so it returns the value of a Sub class variable that is still 0 , since the Sub instance variables are not yet initialized (they are initialized only after executing the constructor Sup ).

+14
source share

All Articles