简体   繁体   English

java中的超类和子类之间是否共享实例变量

[英]Is instance variable shared between super class and sub class in java

class A{
 String foo="bar";
 void m(){

 }
}

class B extends A{
//String foo="xyz";
void m(){
    foo="xyz";
    System.out.println(foo);
    System.out.println(super.foo);
}
}

public class Dell{
 public static void main(String[] args)
    {
    A a=new B();
    System.out.println(a.foo);
    a.m();

}
}

Here is foo variable shared between super class (A) and sub class (B).When I called super.foo in m() method why doesnt it called A class foo variable value that is bar.It seems that foo is shared between both the classes.Bu how is this possible?这是在超类(A)和子类(B)之间共享的 foo 变量。当我在 m() 方法中调用 super.foo 时,为什么它不调用 A 类 foo 变量值,即 bar。似乎 foo 在两者之间共享类。但是这怎么可能? When we declare A with foo variable then it has its own copy and now when we overirde it and changed foo value in child class then how it is reflected back in Super class?当我们用 foo 变量声明 A 时,它有自己的副本,现在当我们覆盖它并更改子类中的 foo 值时,它如何反映回 Super 类? Kindly explain we concepts in well way请很好地解释我们的概念

This is essentially what you need to understand about instance variable scope within super and subclasses.这基本上是您需要了解的关于超类和子类中的实例变量范围的内容。

http://www.xyzws.com/javafaq/what-is-variable-hiding-and-shadowing/15 http://www.xyzws.com/javafaq/what-is-variable-hiding-and-shadowing/15

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

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