package test;
public class PoliTest {
public static void main(String[] args) {
Parent p = new Child1();
// 正确,引用指的对象其实是Child类的实例,执行的是Child类的p1方法
p.p1();
// 错误,虽然引用指的对象是Child类的实例,但是Parent类型的引用找不到对应的方法
p.c1();
}
}
class Parent {
public void p1() {
System.out.println("parent p1");
}
public void p2() throws RuntimeException {
System.out.println("parent p2");
}
}
class Child1 extends Parent {
public void p1() {
System.out.println("chlid1 p1");
}
public void c1() {
System.out.println("child1 c1");
}
}
class Child2 extends Parent {
/**
* 错误,子类如果要重写父类的方法,方法修饰符的权限一定要大于或者等于父类方法修饰符的权限
*/
protected void p1() {
System.out.println("Child2 p1");
}
/**
* 错误,子类如果要重写父类的方法,如果父类有声明抛异常,子类要抛的异常范围只能小于或者等于父类抛的异常范围
*/
public void p2() throws Exception {
System.out.println("Child2 p2");
}
}
多态是个运行时的行为,不是编译时的行为
关于多态
最新推荐文章于 2023-03-09 18:01:17 发布