1、 用Java编写一个Cat类,数据成员包括猫的名称、体重、年龄、毛色、属种;成员方法包括吃东西、睡觉、玩东西。要求写出测试结果
时间: 2023-10-13 19:04:57 浏览: 83
以下是Cat类的Java代码:
```java
public class Cat {
private String name; // 猫的名称
private double weight; // 体重
private int age; // 年龄
private String color; // 毛色
private String breed; // 属种
// 构造方法
public Cat(String name, double weight, int age, String color, String breed) {
this.name = name;
this.weight = weight;
this.age = age;
this.color = color;
this.breed = breed;
}
// 吃东西方法
public void eat() {
System.out.println(name + "正在吃东西。");
}
// 睡觉方法
public void sleep() {
System.out.println(name + "正在睡觉。");
}
// 玩东西方法
public void play() {
System.out.println(name + "正在玩东西。");
}
// 测试方法
public static void main(String[] args) {
Cat cat1 = new Cat("Tom", 3.5, 2, "白色", "英短");
Cat cat2 = new Cat("Jerry", 2.0, 1, "灰色", "蓝猫");
cat1.eat();
cat1.sleep();
cat1.play();
cat2.eat();
cat2.sleep();
cat2.play();
}
}
```
测试结果:
```
Tom正在吃东西。
Tom正在睡觉。
Tom正在玩东西。
Jerry正在吃东西。
Jerry正在睡觉。
Jerry正在玩东西。
```
以上输出结果表明,Cat类的各个方法均能正常执行。