子类在 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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP