简体   繁体   English

在Java中,如何从父方法访问子实例的私有静态属性?

[英]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 :) 谢谢 :)

You can set the A variable in the Child's constructor: 您可以在Child的构造函数中设置A变量:

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. 但是我认为您最好给父母的变量一个getter和setter,然后根据需要从孩子或父母那里设置或获取它。 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. 其他建议:学习并遵循Java命名规则。 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. 如果您要其他人尽力免费帮助您,则并不是要您做同样的事,而是要用真实的代码提出一个体面的问题,以免产生帮助。您比需要的还要困难。

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. 在您的实例中,如果您使用Child类构造函数设置A的值,而不是重新声明变量,则父类应该能够获取该值。

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. 但是,有一种更巧妙的方法可以让多个子类设置变量值,并由超类使用该方法:让子类设置所需的值,然后让超类引用该变量(可能使用吸气剂)该子类已设置其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM