1

privateサブクラスから親クラスのフィールドにアクセスする方法はありますか? すなわち:

public class parent<T> {
    private int MaxSize; 

    ...

}

public class sub extends parent {
    public int getMaxSize() {
        return MaxSize;
    }
}

基本的に、アクセサメソッドgetMaxSize()が の最大サイズを返すようにしArrayQueueます。ありがとう。

4

2 に答える 2

1

No - private fields can only be directly accessed within the class in which they are declared. You could make the field protected, however, which would allow you to access it from subclasses. The table below is a handy reference:

Access permitted by each moodier:

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

[source]

Of course you can also write a public (or protected!) getter method which would just return the value of your field, and use this method in the subclass instead of the actual field itself.

Just as an aside, it is convention to write variable names in camelCase in Java, i.e. maxSize.

于 2012-11-21T19:52:47.867 に答える
1

private variables cannot be accessed from any class other than their declaring class, meaning that subclasses do not have access to private variables of their parent.

You can add a getter in your parent class with public access, which both allow the subclass access. With this structure, your subclass with also inherit getMaxSize() from the parent, removing the need to declare the method in the subclass.

public class Parent {
    private int maxSize;

    public int getMaxSize() {
        return maxSize;
    }
}
于 2012-11-21T19:53:07.020 に答える