I have following questions about the super keyword in java:
I have a code below with classes:
- A Extends no class contains integer variable i
- B Extends class A contains integer variable i
C Extends class B contains integer variable i
class A { int i = 20; A() { System.out.println("I am in constructor of the parent class"); } }
class B extends A { int i = 30; B() { System.out.println("I am in constructor of the subclass"); } }
class C extends B { int i = 40; C() { System.out.println("I am in constructor of the main class"); } void display() { System.out.println(i); System.out.println(super.i); /* * My first thoughts to access the third variable 'i' * inherited indirectly to this class by 'class A'. * I thought that it would print 20 :(. System.out.println(super.super.i); */ } public static void main(String[] argue) { C obj2 = new C(); obj2.display(); } }
- Now as class
B
inherits classA
so it must have two integer variablesi
. ClassC
inherits classB
so it will have two integer variables fromB
and one defined in itself.
- Now as class
Now I can print the inherited super class variable i
in class C
through the display method and of course the variable i defined in class C
itself. The question is how to print the third i
which has the value "20".
I know I can define a method in the class B that returns super.i; and call it through its object in class A that will print the third variable i and I also known that I can create an object of class A, but is there any other way by using super or any other thing to directly access the third variable in the class C.
Also the output is:
I am in constructor of the parent class
I am in constructor of the subclass
I am in constructor of the main class
40
30
why like the this keyword the super keyword cannot be used inside static methods?
why is the super class constructor called to initialize the inherited variables of a subclass? This doesn't make any sense because if a class extends another class the variables and methods will be like they were locally declared in the class in other words its own members. So why can't the constructor of the subclass initialize those inherited members and has to call the super class constructor to initialize them.
A.i
toprivate
. This shouldn't cause a problem, the code should compile and work just as before. But how would thenB
s constructor initialise it?