Home > front end >  why can't we access parent class instance variables inside the class outside the method in chil
why can't we access parent class instance variables inside the class outside the method in chil

Time:12-28

class Demo1{
  int age=12;
  public void display(){
   System.out.println("InDemo1");
  }
}

class Demo2 extends Demo1{
    age=19;   **//------------------->getting error here**
    @Override
    public void display(){
        
        System.out.println("InDemo2" age);
    }
    public Demo2(){
      System.out.println("Inside the constructor");
    }
}


public class SuperKeyword {
    public static void main(String[] args){
        Demo2 demo2=new Demo2();
        demo2.display();
    }
}

I getting compile time error in class Demo2 by using super.age (or) creating a object of Demo1 and acessing the age variable is also giving me compile time error like unidentified token.

I tried to modify the inherited age variable from Demo1 inside the method or constructor in Demo2 class, it is working but, I can't understand we can't we accessed outside the method or constructor in demo2 class

public class SuperKeyword {
    public static void main(String[] args){
        Demo2 demo2=new Demo2();
        demo2.display();
    }
}
class Demo1{
    int age=12;
    public void display(){
        System.out.println("InDemo1");
    }
}

class Demo2 extends Demo1{
    public void display(){
        super.age=19;  //---------->not getting error
        System.out.println("InDemo2" age);
    }

CodePudding user response:

That age=19; is outside of any method or initializer block and thus would need to be a variable declaration like int age=12;. Note that during variable declaration you may define an initial value but you don't have to, i.e. int age; would be fine too.

What you want to do is set a new value when the instance is initialized which is what initializer blocks are for:

class Demo2 extends Demo1 {
  //this is an instance initializer block      
  {
    age=19;
  }

  //rest of your code
}

Initializer blocks are executed before the constructor for the respective class in the hierarchy, i.e. in the case above the order would be:

  • Demo1() constructor
  • { age=19; } block
  • Demo2() constructor

Also note that you can add the static keyword to an initializer block in which case it is executed once when the class is loaded.

  • Related