优化 m.move(); d.move(); System.out.println("老鼠的名字为:" +m.name+ ",年龄:"+m.age+ ",颜色:"+m.color); System.out.println("小狗的名字为:" +d.name+ ",年龄:"+d.age+ ",颜色:"+d.color); d.capture(m);
时间: 2023-11-27 08:51:40 浏览: 50
Java面向对象程序设计方案练习题.doc
可以将重复的代码提取出来,避免代码冗余,比如:
```java
public static void main(String[] args) {
Mouse m = new Mouse("Jerry", 2, "灰色");
Dog d = new Dog("Snoopy", 3, "白色");
System.out.println("老鼠的信息:" + m.getInfo());
System.out.println("小狗的信息:" + d.getInfo());
d.capture(m);
}
```
其中,`Mouse` 和 `Dog` 类中可以定义 `getInfo()` 方法,用于返回对象的信息字符串,避免每次都手动拼接字符串。比如:
```java
class Mouse {
String name;
int age;
String color;
Mouse(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
String getInfo() {
return "老鼠的名字为:" + name + ",年龄:" + age + ",颜色:" + color;
}
}
class Dog {
String name;
int age;
String color;
Dog(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
String getInfo() {
return "小狗的名字为:" + name + ",年龄:" + age + ",颜色:" + color;
}
void capture(Mouse m) {
System.out.println(name + "抓住了" + m.name);
}
}
```
这样可以使代码更简洁、易读。
阅读全文