private 修饰的属性能被继承,只是无法访问!
package Test11;
class Father {
int i = 1;
private int j = 10;
public int getI() {
return i;
// return this.i ???
}
public int getJ() {
return j;
// return this.j; ??
}
}
class Son extends Father {
int i = 2;
int j =20;
public int getI() {
return i;
}
}
public class Test222 {
public static void main(String[] args) throws Exception {
Son s = new Son();
// Father f=new Son();
System.out.println(s.getI());//2
System.out.println(s.getJ()); // 10
// System.out.println(f.getJ());
// Class <?> c = Class.forName("Test11.Son");
// Class< ?> b=c.getSuperclass();
// Field[] s = b.getDeclaredFields();
// for (Field field : s) {
// System.out.println(field.getName());
// }
//
}
}
Java中只有虚方法是多态的 ,字段永远不参与多态。所以当father.getJ()里写renturn j ; 的时候 ,这个j 就只会指father.j 而不会指son.j。
虚方法: 非private的,非static且非final的方法
由于子类中没有重写getJ()方法 所以 返回的是父类中的j;
子类重写了getI()方法且,定义个自己的变量i 则发生遮蔽 (遮蔽了父类的I)