+ -
当前位置:首页 → 问答吧 → 类别多型问题??

类别多型问题??

时间:2011-09-24

来源:互联网

小弟在阅读java se6全方位的类别多型,说到下面有一段code "Animal animal = new Ostrich();", 书上写说用这段code指的是 "只能把ostrich物件当成Animal类别的物件来看. 而且在下面code执行到animal.move() 结果是印出running,是去跑ostrich类别里面的move method.

可是在书中的7-1-4介绍多型,有说过一段"如果把哈雷(无尾熊)当成动物来看时,那么只能使用和存取动物类别所提供的属性跟方法. 所以在这边 当下面主程式执行到animal.move(),怎不是去执行animal的move method, 而是去执行ostrich的move method.

还请各位大大给予小弟指导, 感谢^^

1
2
3
4
5
6
7
8
9
10
11
public class Zoo
{
  public static void main(String argv[])
  {
    Animal animal = new Ostrich();
    
    System.out.println(animal.getKind()+" has "+ animal.getLegs()+" legs.");
    animal.move(); }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Ostrich extends Bird
{
  public Ostrich()
  {
    setLegs(2);
    setKind("Ostrich");
  }
  
  public void move()
  {
    System.out.println("Running");
  }
  
  public void hideHead()
  {
    System.out.println("Hidding the head...");
  }
}
 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class Animal
{
  private int legs;
  private String kind;
  
  public Animal()
  {
    setLegs(4);
  }
  
  public Animal(int l)
  {
    setLegs(l);
  }
  
  public void eat()
  {
    System.out.println("Eating");
  }
    
  public void move()
  {
    System.out.println("Moving");
  }
  
  public void setLegs(int l)
  {
    if (l != 0 && l != 2 && l != 4)
    {
      System.out.println("Wrong number of legs!");
      return;
    }
    
    legs=l;
  }
  
  public int getLegs()
  {
    return legs;
  }
 
  public void setKind(String str)
  {
    kind=str;
  }
  
  public String getKind()
  {
    return kind;
  }
}
 

作者: jarekhuang   发布时间: 2011-09-24

因Animal为Ostrich的父类,父类的变数可以参考子类,所以可以用
1
Animal animal = new Ostrich()

骨子里a还是一个Ostrich, 所以当执行a.move(),所执行的是Ostrich的move()
另外这个时候a并不能去使用到在Ostrich新定义出来的函式,因为宣告animal是一个Animal,所以animal并不知道其子类Ostrich有定义任何新函式(假若Ostrich有定义的话),这就是你说的无尾熊的问题
你可以想成,每个在Animal 定义出来可继承的函式,都有一条线,当有子类重写父类函式时,那条线会延长子类去,但当子类自己产生出来的函式,父类没有线去连到子类,所以当你用父类的变数来创建子类时,父类这端看不到子类建立的函式,所以当然没有办法使用

作者: tw00167789   发布时间: 2011-09-24

热门下载

更多