父类的私有变量和私有方法是否由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)