简体   繁体   English

覆盖从子类定义的静态变量是否会影响父类中所述变量的值?

[英]Does overriding a static variable defined from a sub-class influence the value of said variable in parent class?

I come to you with a simple OOP question. 我向您提出一个简单的OOP问题。 Let's say there are three classes - A, B and C. B and C both inherit a static variable from A. Let's also say that A defines the value of this variable as being 0. Let's say that both B and C modify the value of this static variable. 假设存在三个类-A,B和C。B和C都从A继承静态变量。还说A将该变量的值定义为0。假设B和C都修改了A的值。此静态变量。 My question is this - since static variables remain constant across members of the same class, does this mean that setting the value of a variable of a superclass from a subclass will have no effect on the value of the super class? 我的问题是-由于静态变量在同一类的成员之间保持不变,这是否意味着从子类中设置超类的变量的值对超类的值没有影响?

In other words, if we change the value of B's variable to 1, that value will only be 1 for objects of class B and not C or A? 换句话说,如果我们将B变量的值更改为1,那么对于B类的对象,该值将仅为1,而对于C或A,则该值将不为1?

静态字段仅属于一个类,其子类不继承

Here you can find simple java implementation for your problem. 在这里,您可以找到针对您问题的简单Java实现。
The results can interpret solution. 结果可以解释解决方案。

 class A {
   static int variable = 0;
}

class B extends A{

}
 class C extends A{

}

public class Runclass {

    public static void main(String arg[]){
        A a = new A();
        System.out.println("A "+a.variable);

        B b = new B();
        System.out.println("B "+b.variable);

        C c = new C();
        System.out.println("C "+c.variable);

        b.variable=1;
        System.out.println("After modifying B "+b.variable);
        System.out.println(" A "+a.variable);

    }
}

Output: 输出:

A 0
B 0
C 0
After modifying B 1
A 1

static doesn't mean constant. 静态并不意味着常数。 final means that you can't change the value. final表示您无法更改该值。
You can reach the variable in the superclass A and change it, using this code for example in B: A.someVariable=1; 您可以使用超代码A中的以下代码访问超类A中的变量并对其进行更改:A.someVariable = 1;
After this, you will see the value 1 from C, B and A too, if you use the superclass A variable (A.someVariable). 此后,如果您使用超类A变量(A.someVariable),您还将从C,B和A中看到值1。
I give you a code example: 我给你一个代码示例:

package teszt;

class A {
    static int statValami=0;
}


package teszt;

class B extends A{
    void writeOut(){
        A.statValami=1;
        System.out.println(statValami);
    }
}


package teszt;

class C extends A {
    void writeOut(){
        A.statValami=100;
        System.out.println(statValami);
    }
}


package teszt; 包teszt;

class Over  {
    public static void main(String args[]){
        new B().writeOut();
        new C().writeOut();
        System.out.println(A.statValami);
    }
}



OUTPUT is: 输出是:
1 1个
100 100
100 100

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

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