first piece of Code is giving the output as below
From super Contsrutor 30
From Sub e=0,b=0
This is because of below reason.
first thing when we do new Child()
, the constrcutor of Child class starts execution
but its first statement is super by default so it gives a call to parent class constrctor
now Parent class constrcutor has below code
Parent(){
System.out.println("From super Contsrutor "+a);
meth();
}
so here parent class is calling meth() method and its caller is actually a subclass child's object so it calls child class meth() method.
now when it calls child class meth() method from super constrcutor actually child object
is not yet created so its variables are not yet initialized but we are printing the values for both a and b.
so b gets 0 before getting assigned after child constrcutor gets execution completed.
so changing your first piece of code like below will give desired output
ie putting meth() call inside child constrctor rather than on parent constrcutor.
package com.kb.finalVariables;
public class Test {
public static void main(String args[]){
Child c1 = new Child();
}
}
class Parent{
final int a =30;
Parent(){
System.out.println("From super Contsrutor "+a);
// meth();
}
void meth(){
System.out.println("From super");
}
}
class Child extends Parent{
final int e=super.a;
int b=30;
public Child() {
meth();
}
void meth(){
System.out.println("From Sub e=" +e+", b="+b);
}
}