访问私有父属性的最佳做法?

时间:2018-01-10 13:36:45

标签: java oop

想象一下,您有两个类,Parent类和继承自Child的{​​{1}}类。 Parent的属性Parent设置为私有,子类的a方法需要访问doSomething(),如:

a

我的问题是:是否有从public class Parent { private Attriute a; public Parent(Attribute a) { this.a = a; } } public class Child extends Parent { public Child(Attribute a) { super(a); } public void doSomething() { // Need to access to a here } } 访问a的最佳方式?关于如何继续,我几乎没有想法:

  • Child中设置a的{​​{1}}的可见性,但随后protected可以访问,并且可以在包中进行修改。
  • Parent的{​​{1}}中创建一个受保护的getter,但它也可以在包中的evrywhere中访问。
  • a类中创建一个新的私有Parent字段,并在构造函数中将a保存到其中。像这样的新的'属性只能从Attribute访问,并且它与Child属性相同,但它也会重复'两个班级都a

但我不知道哪一个是最好的,也许这些都不是,所以帮助!!

2 个答案:

答案 0 :(得分:1)

在Java中,没有办法将成员访问子类,而不将其授予同一个包中的所有类。

只需为该字段添加一个getter方法,并将其设为protected。这提供了比您更喜欢的访问权限,但通常可以接受。

如果封装很关键,您可以将类移动到其包中,并阻止以这种方式允许访问非子类。

答案 1 :(得分:-1)

This也许就是你要找的东西。

创建返回private属性的受保护方法,以及限制因此只有子类可以获取属性。

public class Parent {
    private Attribute a;
    public Parent(Attribute a) {
        this.a = a;
    }
    protected Attribute getA() throws IllegalAccessException, ClassNotFoundException {
        if(!getClass().isAssignableFrom(
        Class.forName(new Throwable().getStackTrace()[1].getClassName()))) {
            throw new IllegalAccessException(
                "This method can be accessed by subclass only");
        }
        return a;
    }
}

public class Child extends Parent {
    public Child(Attribute a) {
        super(a);
    }
    public void doSomething() throws IllegalAccessException, ClassNotFoundException {
        Attribute a = getA();
    }
}
相关问题