问题描述:

So I if I have two classes like this:

public class A extends B{

public String name = "Alpha"

}

public class B{

public void revealAName(){

print(this.name);

}

}

main(){

A newA = new A();

newA.revealName();

}

In this case Eclipse says that the attribute name doesn't exist. Why does it say that? why cant I use class A-objects' attributes when I'm inside class B's methods? How can I fix it?

网友答案:

B doesn't know anything about attributes in A, both classes could be compiled separately.

But if you change it so that B extends A, you can access name from the derived class (B):

class A {
    String name = "Alpha";
}

class B extends A {
    public void revealAName(){
        print(this.name);
    }
}
A a = new A();
a.name; // OK
a.revealName(); // not OK

B b = new B();    
b.name; // OK
b.revealName(); // OK

See also the Oracle tutorial on inheritance

网友答案:

First of all, there should be only one public class that should contain the main method. Secondly, You are using inheritance. So, You have to give access modifier of your base class's variables to "protected" in order to access in your child classes. So, it should be:

protected String name = "Alpha";

because "default" access modifier won't allow access for child class. From controlling access to members of class

 Modifier       Class   Package Subclass World   
 public         Y       Y       Y        Y  
 protected      Y       Y       Y        N  
 no modifier    Y       Y       N        N  
 private        Y       N       N        N 

Another thing, you used 'this.name' that is trying to get the 'name' variable of class B. That's why it's showing error.

While using inheritance, You can directly use the parent class's variable without using any object reference OR You can use "super" for object reference in case of duplicate variable names. You can refer this image in case of doubt..

Hope, It would be clear now.

相关阅读:
Top