如何从父类访问私有字段

时间:2015-11-07 23:27:59

标签: java class inheritance

我正在测试各种组合来构建超类和子类,我意识到当我执行以下操作时无法从父类访问私有字段:

abstract class Ball{
    private int size;
    protected Ball(int size){
        this.size = size;
    }    
    public abstract void setSize(int size);  
    public abstract int getSize();           
}

class SoccerBall extends Ball
{
    public SoccerBall(int size){
        super(size);
    }
    @Override
    public void setSize(int size){this.size = size;}//size not inherited
    @Override
    public int getSize(){return size;}              //size not inherited    
}

我知道私有字段不会被继承到子类。

是使用getter和setter的唯一方法(可能除了反射之外唯一的方法)。

所以我的问题:

Q1 )如果我想将父类中的字段保持为私有而不受保护。我应该 制作getter和setter摘要,以使其子字段可以访问私有字段吗?

Q2 )如果我要将字段(大小)设为私有,我应该如何实现我的getter和setter以使子类可以访问私有字段?

2 个答案:

答案 0 :(得分:0)

不要直接尝试访问该值,而是将大小的访问级别更改为" protected"。这样,它将被大部分封装,除非由子类访问。

答案 1 :(得分:0)

  

如果我想将父类中的字段保持为私有而不受保护。我是否应该使getter和setter摘要以使其子字段可以访问私有字段?

是的,因为该字段是私有的,只有在父类中定义了getter和setter才能访问。不应将getter和setter声明为abstract。

  

如果我要将字段(大小)设为私有,我应该如何实现我的getter和setter以使子类可以访问私有字段?

只需在私有字段所在的父类中实现一个普通的getter和setter。

0

子类

abstract class Ball{
    private int size;
    protected Ball(int size){
        this.size = size;
    }    
    protected void setSize(int size){
        this.size = size;
    }
    protected int getSize(){
        return size;
    }          
}