我有主课:

public class MainClass{
    private int firstVal;
    private int secVal;

    public MainClass(int firstVal,int secVal){
      this.firstVal=firstVal;
      this.secVal=secVal;
    }
}


第二类扩展了这一类

 public class SecClass extends MainClass{
     public SecClass(int firstVal,int secVal){
         super(firstVal,secVal)
     }
 }


我想知道如何在SecClass中使用值firstVal和secVal?
    super.firstVal吗?
还是我必须确定agian中的值?

谢谢

最佳答案

只需将它们标记为protected而不是private

public class MainClass {
    protected int firstVal;
    protected int secVal;
    //rest of your class...
}


如果要将它们保留为private,则可以为此字段创建getter和setter并将这些方法标记为publicprotected,这取决于您希望/需要的可见性:

public class MainClass {
    private int firstVal;
    //its value can be retrieved by any class
    public int getFirstVal() {
        return this.firstVal;
    }
    //its value can only be modified by subclasses of MainClass
    protected void setFirstVal(int firstVal) {
        this.firstVal = firstVal;
    }
    //similar for the other field...
}

08-06 17:15