1 package test;
2
3 public class PoliTest {
4
5 public static void main(String[] args) {
6 Parent p =
new Child1();
7 // 正确,引用指的对象其实是Child类的实例,执行的是Child类的p1方法
8 p.p1();
9 // 错误,虽然引用指的对象是Child类的实例,但是Parent类型的引用找不到对应的方法
10 p.c1();
11
12 }
13
14 }
15
16 class Parent {
17
18 public void p1() {
19 System.out.println("parent p1"
);
20 }
21
22 public void p2()
throws RuntimeException {
23 System.out.println("parent p2"
);
24 }
25
26 }
27
28 class Child1
extends Parent {
29
30 public void p1() {
31 System.out.println("chlid1 p1"
);
32 }
33
34 public void c1() {
35 System.out.println("child1 c1"
);
36 }
37 }
38
39
40 class Child2
extends Parent {
41
42 /**
43 * 错误,子类如果要重写父类的方法,方法修饰符的权限一定要大于或者等于父类方法修饰符的权限
44 */
45 protected void p1() {
46 System.out.println("Child2 p1"
);
47 }
48
49 /**
50 * 错误,子类如果要重写父类的方法,如果父类有声明抛异常,子类要抛的异常范围只能小于或者等于父类抛的异常范围
51 */
52 public void p2()
throws Exception {
53 System.out.println("Child2 p2"
);
54 }
55
56 }
多态是个运行时的行为,不是编译时的行为
转载于:https://www.cnblogs.com/billmiao/p/9872186.html
相关资源:各显卡算力对照表!