Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how access a private static attribute of a child instance from parent method?

Here is an example :

class Parent {
    protected int A;

    public void displayA() {
        System.out.println(A);
    }
}

class Child extends Parent {
    protected static int A=2;
}

Child intance = new Child();
intance.displayA();

=> return null !!!

What is the way to retrieve the child attribute from parent method ?

Thank you :)

like image 494
nonozor Avatar asked Aug 19 '12 15:08

nonozor


2 Answers

You can set the A variable in the Child's constructor:

class Child extends Parent {
   // protected static int A=2; // this redeclares the variable -- it's a different variable

   public Child() {
      A = 2;
   }
}

But I think you're better off giving the parent's a variable a getter and setter, and set or get it from the child or parent as needed. In my mind this is better than to manipulate fields directly since you can then monitor the field for changes and do actions if the data being changed is inappropriate.

Other suggestions: learn and stick to Java naming rules. Also your posted code has many careless errors in it including typos. If you are asking others to put in the effort to try to help you for free, it's not asking too much to ask you to do the same -- put in the effort to ask a decent question with real code so as not to make helping you any more difficult than it needs to be.

like image 57
Hovercraft Full Of Eels Avatar answered Sep 28 '22 05:09

Hovercraft Full Of Eels


In your instance if you use your Child class constructor to set the value of A rather than redeclaring the variable then the parent class should be able to get the value.

The problem with the instance above is that you are redeclaring the variable in your sub class rather than just altering the value of the variable in your superclass.

Is there a reason that you have the child variable declared as static? If you only need the value of that class variable then you can reference it directly. However a neater way to have the potential for multiple subclasses to set the variable value and it be used by the super class is to have the child classes set the value you want and then have the super class reference that variable (possibly using a getter) that the subclass has set the value of.

like image 27
Elliott Hill Avatar answered Sep 28 '22 06:09

Elliott Hill