JAVA 用polymorphism一道題目的問題
高洛峰
高洛峰 2017-04-17 18:00:01
0
4
722

一问题是这样的:
先建立一个Animal的 class 是 abstract
Animal有 move() 这个方法
接着有 狗、人、鸟三个class 分别的移动是 "四只脚 "&"两只脚" & "翅膀"
都继承自Animal
继承Animal的类别,必须改写其move方法
并显示出每种动物的移动方式

说明:
 Animal不存在的,他不会真的"move",也不能被实例化
在建立出各种动物的Subcategory(子类别) 物件时,将这些物件放入同一个阵列中
利用回圈方式,印出所有动的讯息

我只写的出部分功能 但无法把它完整执行
谢谢论坛的朋友们

abstract class Animal{
          public void move(){
              System.out.println();
        }
}



 pulbic  class Dog extends Animal{
    public void move(){
            System.out.println("四只脚");
    }
}


public class Bird extends Animal {
    public void move(){
        System.out.println(" 翅膀 ");
    }
}

public class Human extends Animal {
    public void move(){
        System.out.println("两只脚");
    }
}

public class Main{
    public static void main(String[] args){
      Animal[] animals = new Animal[3];
      animals[0] = new Bird();
      animals[1] = new Human();
      animals[2] = new dog();
      
      for(int i=0;i<animals.length;i++){
          animals[i].make.Sound();
          }
      }
}
    
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
PHPzhong
public abstract class Animal {
    public void move() {
        System.out.println();
    }
}

public class Bird extends Animal {
    public void move() {
        System.out.println( " 翅膀 " );
    }
}
public class Dog extends Animal {
    public void move() {
        System.out.println( "四只脚" );
    }
}

public class Human extends Animal {
    public void move() {
        System.out.println( "两只脚" );
    }
}

public class Main {

    public static void main(String[] args) {
        Animal[] animals = new Animal[3];

        animals[0] = new Bird();

        animals[1] = new Dog();

        animals[2] = new Human();

        for (Animal animal : animals)
            animal.move();
    }
}

Run screenshot

左手右手慢动作

So, what’s the problem? The code you wrote is wrong too

for(int i=0;i<animals.length;i++){
    animals[i].make.Sound();
}

I didn’t see you declare the makeattribute anywhere at all! What exactly are you trying to achieve?

大家讲道理

Change the move method of animal to abstract. I think your question is saying that subclasses must be rewritten.

迷茫
abstract class Animal{
    public abstract void move();
}
class Dog extends Animal{
    public void move(){
            System.out.println("四只脚");
    }
}
class Bird extends Animal {
    public void move(){
        System.out.println(" 翅膀 ");
    }
}
class Human extends Animal {
    public void move(){
        System.out.println("两只脚");
    }
}
public class Main{
    public static void main(String[] args){
      Animal[] animals = new Animal[3];
      animals[0] = new Bird();
      animals[1] = new Human();
      animals[2] = new Dog();
      for(int i=0;i<animals.length;i++){
          animals[i].move();
      }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template