In Java, how to access the private static attribute of a child instance from a 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 get the child attribute from the parent method?

Thanks:)

+4
source share
2 answers

You can set the variable A in the Child constructor:

 class Child extends Parent { // protected static int A=2; // this redeclares the variable -- it a different variable public Child() { A = 2; } } 

But I think that you better give your parents the getter and setter variable, and also set or get it from the child or parent as needed. In my opinion, this is better than manipulating the fields directly, since you can track the field for changes and perform actions if the changed data is not suitable.

Other suggestions: Learn and abide by the Java naming conventions. Your published code also has many careless errors, including typos. If you ask others to make an effort to try to help you for free, it does not require too much to ask you to do the same - try to ask a decent question with real code so as not to help you are more complicated than it should be.

+3
source

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

The problem with the above instance is that you are updating the variable in your subclass, and not just changing the value of the variable in your superclass.

Is there a reason you have a child variable declared as static? If you only need this class variable, you can refer to it directly. However, an easier way is for many subclasses to set the value of the variable and use the superclass so that the child classes set the desired value and then refer to the superclass variable (possibly using a getter) that the subclass sets the value.

+2
source

All Articles