一切来源于一个问题:“如果超类中的方法,没有访问控制,什么限定符都没用,那在子类中覆盖这个方法,并定义成private可以吗,怎么验证呢?”
思路办法:编码测试之~
public class aTest { public void hello() {}} public class bTest extends aTest{ private void hello() {}}/** *编译报错,子类尝试覆盖父类的方法,但是却赋予了较低的权限private */
这么设计,考虑到向上转型,父类引用才能动态连接调用子类的方法,应该是基于这个考虑,如果不太理解原因,可以继续往下看。
以下是扩展测试,有兴趣可以继续看:(先写结论,若知道结论,可以跳过对应段解释)
1.对于父类中定义的方法,如果子类中重写了该方法,那么父类类型的引用将会调用子类中的这个方法,这就是动态连接。
View Code
public class aTest { public void hello() { System.out.println("hello aTest"); } } public class bTest extends aTest{ public void hello() { System.out.println("hello bTest"); }} public class Test { public static void main(String[] args) { aTest a = new bTest(); a.hello(); }}/*Output: hello bTest*///~
2.如果子类没有覆盖父类的方法,父类引用则调用父类中声明的方法。但是父类引用不能调用父类中定义的private方法。
View Code
public class aTest { private hello() {}} public class bTest extends aTest{ } public class Test { public static void main(String[] args) { aTest a = new bTest();//申请bTest对象,用aTest引用指向 a.hello();//!!!编译报错 }}
3.子类可以继承父类的静态属性和静态方法,但是不可以重写静态方法。
View Code
public class aTest { public static void hello() { System.out.println("hello aTest"); } } public class bTest extends aTest{ public static void hello() { System.out.println("hello bTest"); }} public class Test { public static void main(String[] args) { aTest a = new bTest(); a.hello(); }}/*Output: hello aTest*///:~ //解释:因为bTest的hello()方法没有覆盖父类的方法,所以aTest的引用hello(),还是调用父类的方法