写代码:1.基于面向对象的思想,模拟一个猫和老鼠的程序。 要求: 1)猫和老鼠都有名字和体重两种属性,各自都有有参的构造方法,猫有抓老鼠的方法public void catchMouse(Mouse mouse),老鼠则有逃跑的方法 public void escapeCat(Cat cat)。 2)产生一个猫对象和一个老鼠对象,对名字和体重通过有参构造方法进行赋值。若猫的体重大于或等于老鼠的体重,则实现抓老鼠方法;若猫的体重小于老鼠的体重,则实现老鼠逃跑的方法
时间: 2023-05-30 18:05:50 浏览: 127
。// 猫类
class Cat {
private String name;
private double weight;
public Cat(String name, double weight) {
this.name = name;
this.weight = weight;
}
public void catchMouse(Mouse mouse) {
if (this.weight >= mouse.getWeight()) {
System.out.println(this.name + "抓住了" + mouse.getName());
} else {
System.out.println(this.name + "体重太轻,没抓住" + mouse.getName());
}
}
public String getName() {
return this.name;
}
public double getWeight() {
return this.weight;
}
}
// 老鼠类
class Mouse {
private String name;
private double weight;
public Mouse(String name, double weight) {
this.name = name;
this.weight = weight;
}
public void escapeCat(Cat cat) {
System.out.println(this.name + "逃跑了," + cat.getName() + "没抓住!");
}
public String getName() {
return this.name;
}
public double getWeight() {
return this.weight;
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat("Tom", 5.0);
Mouse mouse = new Mouse("Jerry", 2.0);
cat.catchMouse(mouse);
mouse.escapeCat(cat);
}
}
阅读全文