多态也是JAVA面向对象的三大特征之一
多态【方法的多态】【对象的多态】
1、方法的多态:重写,重载
2、对象的多态
a、一个对象的编译类型和运行类型可以不一致
b、编译类型在定义对象时就确定了,不能改变
c、运行类型可以改变【动态绑定机制】
多态的本质:父类的引用指向子类的对象
1 package com;
2 /*
3 * 多态
4 * */
5
6 public class Polymorphism {
7 public static void main(String[] args) {
8
9 //向上转型
10 Animal animal = new Dog("旺财","雄性",8);
11 System.out.println(animal.eat());
12 //输出运行类型
13 System.out.println(animal.getClass());
14 Animal animal1 = new Cat("哈士奇","雌性","精神焕发");
15 System.out.println(animal1.sleep());
16 System.out.println(animal1.getClass());
17
18 //向下转型
19 Dog dog = (Dog)animal;
20 System.out.println(dog.sleep());
21 System.out.println(dog.getClass());
22
23 Cat cat = (Cat) animal1;
24 System.out.println(cat.eat());
25 System.out.println(cat.getClass());
26
27 }
28 }
29 class Animal{
30
31 private String name;
32 private String sex;
33
34 public Animal(String name, String sex) {
35 this.name = name;
36 this.sex = sex;
37 }
38
39 public String sleep(){
40 return sex + name + "正在睡觉";
41 }
42
43 public String eat(){
44 return sex + name + "正在进食";
45 }
46
47 }
48 class Dog extends Animal{
49
50 private int age;
51
52 public Dog(String name, String sex, int age) {
53 super(name, sex);
54 this.age = age;
55 }
56
57 public String sleep(){
58 return age + "岁的" + super.sleep();
59 }
60
61 }
62 class Cat extends Animal{
63
64 private String status;
65
66 public Cat(String name, String sex, String status) {
67 super(name, sex);
68 this.status = status;
69 }
70
71 public String eat(){
72 return status + "的" + super.eat();
73 }
74
75 }