一直認爲默認訪問級別的java 方法對子類是不可見的,也就是不能被繼承的,但是下面的例子挑戰了這個看法
public class TT {
public static void main(String[] args) {
B b=new B();
System.out.println(b.getA());
System.out.println(b.getB());
}
}
class A {
int x = 1;
int getA() {
return x;
}
}
class B extends A {
int x = 2;
int getB() {
return x;
}
}
這個getA明顯是默認訪問級別private,爲什麼B能調用getA()?
原來默認的訪問級別是package-private, 意思是該方法對同一package中的class是可見的,也是可繼承的。
如果把A的類訪問級別改爲public,把B放到另一個package中,那麼B將不能訪問A的getA()方法。