1 package cn.tju.acculation.base;
2
3 public class Extend {
4
5 public static void main(String args[]) {
6 //在方法覆盖中,左右俩边分别为父类和子类的时候,以左边作为调用的入口,右边作为调用的实际调用执行的方法。
7 P t2=
new T();
8 //t2是Parent的对象,t2调用的方法只能是Parent的方法,但是实际调用是调用子类还是父类的方法,是看new谁,new谁就调用谁
9 //只有子类的对象,才能调用子类的方法,以左边作为调用的入口,右边作为调用的实际调用执行的方法
10 t2.m();
//output:this is t.m()
11 //t2.m2();//错误。因为P中没有此方法的入口
12
13 //这里new的是T,parent只是一个强制类型的转换。
14 P t3= (P)
new T();
//强转没有作用
15 t3.m();
//output:this is t.m(),可见此时依旧是以右边作为调用的实际调用执行的方法
16 t3.m3();
//output:this is p.m3(),因为T没有对m3()方法进行重写,所以执行P中的方法
17 }
18 }
19
20 class T
extends P {
21 public void m() {
22 System.out.println("this is t.m()"
);
23 }
24
25 public void m2(){
26 System.out.println("this is t.m2()"
);
27 }
28 }
29
30 class P {
31 public void m() {
32 System.out.println("this is p.m()"
);
33 }
34
35 public void m3() {
36 System.out.println("this is p.m3()"
);
37 }
38 }
转载于:https://www.cnblogs.com/QuentinYo/p/3302191.html