子類在 Java 中是否能繼承父類中的私有變數和私有方法?


不會,子類不能繼承父類的私有成員,它只能繼承父類的受保護的、沒有的和公有的成員。如果你這麼做,編譯時就會出現錯誤:−

示例

class Super{
   private int data = 30;
   public void display(){
      System.out.println("Hello this is the method of the super class");
   }
}
public class Sub extends Super{
   public void greet(){
      System.out.println("Hello this is the method of the sub class");
   }
   public static void main(String args[]){
      Sub obj = new Sub();
      System.out.println(obj.data);
   }
}

執行此示例時,將會出現如下所示的編譯時錯誤:−

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
   The field Super.data is not visible
   at Sub.main(Sub.java:13)

更新於: 2019 年 7 月 30 日

759 次瀏覽

開啟您的 職業 生涯

完成該課程後獲得認證

開始
廣告