码迷,mamicode.com
首页 > 编程语言 > 详细

java多态

时间:2019-06-06 21:31:42      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:new   类型   使用   dog   出错   ext   执行   变量   mon   

多态性

java引用类型有两个

  编译时类型

  编译时类型由声明该变量时使用的类型决定

  运行时类型

  运行时类型由实际赋给该变量的对象决定

例:

 1 class Animal{
 2     public int month = 2;
 3     public void eat(){
 4         System.out.println("动物吃东西");
 5     }
 6     
 7 }
 8 
 9 class Dog extends Animal{
10     public int month = 3;
11     
12     public void eat() {
13         System.out.println("小狗吃肉");
14     }
15     
16     public void sleep() {
17         System.out.println("小狗睡午觉");
18     }
19 }
20 
21 class Cat extends Animal{
22     public int month = 4;
23     
24     public void eat() {
25         System.out.println("小猫吃鱼");
26     }
27 }
28 
29 public class Test {
30     public static void main(String[] args){
31         Animal a = new Dog();
32         Animal b = new Cat();
33         a.eat();
34         System.out.println(a.month);
35         //下面代码编译时会出错
36 //        a.sleep();
37         b.eat();
38         System.out.println(b.month);
39         
40     }
41 }

 

a对象编译时类型是Animal,运行时类型是Dog;

b对象编译时类型是Animal,运行时类型是Cat。

当运行时调用引用变量的方法时,其方法行为总是表现出子类方法的行为特征,而不是父类方法的行为特征,这就表现出:相同类型的变量调用同一个方法时表现出不同的行为特征,这就是多态。

该例中:当他们调用eat方法时,实际调用的是父类Animal中被覆盖的eat方法。

运行结果:

小狗吃肉
2
小猫吃鱼
2

上例中main方法中注释了a.sleep(),由于a的编译时类型为Animal,而Animal类中没有sleep方法,因此无法在编译时调用sleep方法。

对象的实例变量不具备多态性

上例中a,b对象分别调用了month,可以看到,其输出结果都是2

 

总的来说:

引用变量在编译阶段只能调用编译时类型所具有的方法,但运行时则执行他运行时类型所具有的方法。

java多态

标签:new   类型   使用   dog   出错   ext   执行   变量   mon   

原文地址:https://www.cnblogs.com/haiyuexiaozu/p/10986510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!