简体   繁体   中英

Java Extended Class Accessor

Is there a way to access a private field in a parent class from a subclass? ie:

public class parent<T> {
    private int MaxSize; 

    ...

}

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

Basically i want an accessor method, getMaxSize() , to return the maximum size of an ArrayQueue . Thanks.

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:

----------------------------------------------
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, ie axSize . axSize ,在 Java 中以驼峰命名法编写变量名是约定俗成的,即 axSize

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;
    }
}

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