Nannan  2024-06-20 23:35 采纳率: 61.5%
浏览 3

各位专家看看这个java题吧

16.【接口】现在有3种动物:dog、fish,它们行动的方式都不相同,分别是run、swim。设计一个动物
行动模拟器,模拟各种类型动物的行动方式。要求如下:
(1)定义一个接口Animal。接口里有抽象方法Stringmove()。
(2)定义2个子类dog、fish分别实现上述接口。
(3)定义一个模拟器类Simulator。该类有一个StringdemoMotion(Animalanimal)方法,可以根据
具体传入的参数是dog或者fish,调用对应的move方法,返回具体动物的行动方式。
(4)编写窗口类,在其中创建一个模拟器Simulator对象,当点击模拟dog按钮,右侧标签显示“狗
的移动方式是run”。当点击模拟fish按钮,右侧标签显示“鱼的移动方式是swim”。

  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2024-06-20 23:35
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    根据你的要求,下面是一个简单的Java程序设计,用于模拟不同动物的行动方式:

    1. 定义接口 Animal

      public interface Animal {
          String move();
      }
      
    2. 创建子类 DogFish

      public class Dog implements Animal {
          @Override
          public String move() {
              return "run";
          }
      }
      
      public class Fish implements Animal {
          @Override
          public String move() {
              return "swim";
          }
      }
      
    3. 设计 Simulator 类:

      public class Simulator {
          public String demoMotion(Animal animal) {
              return animal.move();
          }
      }
      
    4. 编写窗口类(这里使用Swing框架作为示例):

      import javax.swing.*;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      
      public class AnimalSimulatorUI extends JFrame {
          private Simulator simulator;
          private JLabel actionLabel;
      
          public AnimalSimulatorUI() {
              simulator = new Simulator();
              actionLabel = new JLabel("请选择动物进行模拟");
      
              JButton dogButton = new JButton("模拟Dog");
              JButton fishButton = new JButton("模拟Fish");
      
              dogButton.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      actionLabel.setText("狗的移动方式是" + simulator.demoMotion(new Dog()));
                  }
              });
      
              fishButton.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      actionLabel.setText("鱼的移动方式是" + simulator.demoMotion(new Fish()));
                  }
              });
      
              this.add(dogButton);
              this.add(fishButton);
              this.add(actionLabel);
      
              this.setSize(300, 200);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLayout(new FlowLayout());
              this.setVisible(true);
          }
      
          public static void main(String[] args) {
              new AnimalSimulatorUI();
          }
      }
      

    请注意,上述代码中的窗口类 AnimalSimulatorUI 使用了Java Swing框架来创建图形用户界面。你需要确保你的开发环境中已经包含了Swing库。

    此外,如果你需要进一步的帮助,例如如何运行Java程序,或者如何设置Java开发环境,你可以访问以下链接:

    希望这能帮助你完成你的Java程序设计!如果有任何问题,随时欢迎提问。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 6月20日