简体   繁体   中英

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? 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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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