多态

多态:相同的一条语句,在不同的运行环境中可以产生不同的运行结果。

简单多态只可赋方法不可赋变量。

子类对象可以直接赋给基类变量。

基类对象要赋给子类对象变量,必须执行类型转换,其语法是:
子类对象变量=(子类名)基类对象名;

一.动手动脑

1 public class ParentChildTest {
 2     public static void main(String[] args) {
 3         Parent parent=new Parent();
 4         parent.printValue();
 5         Child child=new Child();
 6         child.printValue();
 7         
 8         parent=child;
 9         parent.printValue();
10         
11         parent.myValue++;
12         parent.printValue();
13         
14         ((Child)parent).myValue++;
15         parent.printValue();
16         
17     }
18 }
19 
20 class Parent{
21     public int myValue=100;
22     public void printValue() {
23         System.out.println("Parent.printValue(),myValue="+myValue);
24     }
25 }
26 class Child extends Parent{
27     public int myValue=200;
28     public void printValue() {
29         System.out.println("Child.printValue(),myValue="+myValue);
30     }
31 }

结果截图;

结果分析:

      a. 当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定。这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

      b.如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。
      c.如果子类被当作父类使用,则通过子类访问的字段是父类的!

二.动手动脑 动物园

 1 import java.util.Vector;
 2 public class zoo4 {
 3     public static void main(String[] args) {
 4          Feeder f = new Feeder("小李");
 5          Vector<Animal> ans = new Vector<Animal>();
 6 
 7          //饲养员小李喂养一只狮子
 8          ans.add(new Lion());
 9          //饲养员小李喂养十只猴子
10          for (int i = 0; i < 10; i++) {
11              ans.add(new Monkey());
12          }
13          //饲养员小李喂养5只鸽子
14          for (int i = 0; i < 5; i++) { 
15              ans.add(new Pigeon());
16          }
17                 
18          f.feedAnimals(ans);
19    }
20 }
21 
22 class Feeder {//饲养员类
23     public String name;
24     Feeder(String name) {
25         this.name = name;
26     }
27     public void feedAnimals(Vector<Animal> ans) {
28         for (Animal an : ans) {
29             an.eat();
30             }
31         }
32 }
33 
34 interface Animal {//动物基类
35     public abstract void eat();
36         }
37 
38 class Lion implements Animal {//狮子类
39     public void eat() {
40         System.out.println("我不吃肉谁敢吃肉!");
41             }
42 }
43 
44 class Monkey implements Animal {//猴子类
45     public void eat() {
46         System.out.println("我什么都吃,尤其喜欢香蕉。");
47             }
48 }
49 
50 class Pigeon implements Animal {
51     public void eat() {
52         System.out.println("我要减肥,所以每天只吃一点大米。");
53         }
54 }

结果截图:

原文地址:https://www.cnblogs.com/du1269038969/p/6079332.html