子類在 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)
廣告