子类在继承父类的时候,首先应该满足父类可被访问,例如当子类和父类不在同一个包当中时,父类修饰符必为public;在父类能被访问的前提下,凡是修饰符为public或是protected的父类属性成员或方法能被子类访问;private的属性成员或是方法则不能被直接访问。子类不能直接访问父类的private属性和方法,可以调用父类的公共方法来间接访问私有属性。
程序验证,代码如下:
public class Father {
private int father1 = 1;
private void getFather1()
{
System.out.println("father1: "+father1);
}
protected int father2 = 2;
protected void getFather2()
{
System.out.println("father2: "+father2);
}
public int father3 = 3;
public void getFather3()
{
System.out.println("father3: "+father3);
}
}
public class Son extends Father{
public static void main(String[] args) {
Son son = new Son();
int son1 = son.father1;
int son2 = son.father2;
int son3 = son.father3;
son.getFather1();
son.getFather2();
son.getFather3();
}
}
//此时程序会出现错误,错误原因如下:
//'father1' has private access in 'Father'
//'getFather1()' has private access in 'Father'
总结:
子类继承了父类的所有属性和方法,但是只有public和protecte的属性和方法在子类是可见的