Java多态--父类引用指向子类对象

其实这个我最近想明白了,是因为遇到了一段预测失败的代码很简单哈
首先 重载 和 重写是不同的,哪里不同这里不说,留到另外的日志。
首先看这个代码,这里面只有重载没有重写:
01  public   class   testInter   {
02 
03       public   static   void   main ( String []   args {
04           A   a   =   new  B();
05          B b  =   new  B();
06           a . m ( 5 );
07           //a.m(1.1);
08          b . m ( 1 );
09          b . m ( 1.1 );
10       }
11  }
12 
13  class   A {
14       protected   int   i ;
15       public   void   m ( int   i )
16       {
17           this . i   =   i ;
18           System . out . println ( A + this . i );
19       }
20  }
21 
22  class   extends   A
23  {
24       double   d ;
25       public   void   m ( double   d )
26       {
27           this . d   =   d ;
28           System . out . println ( B + this . d );
29       }
30  }
这里我第一个是用父类引用指向子类对象,第二个就是普通的直接实例化B;
他的输出
A5
B1
B1.1
中间我注释掉了a.m(1.1)是因为它会报错,为什么?因为对于a来说它只能调用m(int i)也就是说只能调用父类的方法,除非它被重写(这就是其中重要的不同)。
同样我把代码改下:
01  public   class   testInter   {
02 
03       public   static   void   main ( String []   args {
04           A   a   =   new  B();
05          B b  =   new  B();
06           a . m ( 1 );
07          b . m ( 2 );
08       }
09 
10  }
11 
12  class   A {
13       protected   int   i ;
14       public   void   m ( int   i )
15       {
16           this . i   =   i ;
17           System . out . println ( "AAA" );
18       }
19  }
20 
21  class   extends   A
22  {
23       double   d ;
24       public   void   m ( int   d )
25       {
26           this . d   =   d ;
27           System . out . println ( "BBB" );
28       }
29  }
看,这次m方法是被重写了,那么输出是什么?
BBB
BBB
这就是结果,所以呢,很简单了,看到调用的方法,千万别乱了~~
有错误之处,请指出,谢谢~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值