priviate限制访问方式只能在类的内部,这仅仅只是一个访问控制, 实际上,父类的私有属性也可以被子类继承,只是不可直接访问而已, 另外,子类其它是可以从继承的一个public方法(或者get,set方法),去访问到父类的private变量或方法。
class Parent{
private Thread exclusiveOwnerThread;
private int num=10;
protected Thread getExclusiveOwnerThread() {
return exclusiveOwnerThread;
}
protected void setExclusiveOwnerThread(Thread exclusiveOwnerThread) {
this.exclusiveOwnerThread = exclusiveOwnerThread;
}
protected int getNum(){
return num;
}
}
class Son extends Parent {
public static void main(String[] args) {
Son son = new Son();
System.out.println(son.getExclusiveOwnerThread());
son.setExclusiveOwnerThread(Thread.currentThread());
System.out.println(son.getExclusiveOwnerThread());
System.out.println("子类无法访问父类的私有成员变量,尽管在子类不可见,但是子类仍会继承父类的私有属性,可通过继承的get,set方法来操作和获取");
System.out.println("son's num:"+son.getNum());
}
}
可以看到,子类其实是继承了父类的私有属性的,需要通过方法来操作。