Java编写一个cat类,数据成员包括名称,体重,年龄 ,毛色,属种;成员方法包括吃东西,睡觉,玩东西
时间: 2024-06-11 16:09:59 浏览: 14
以下是Java编写的Cat类:
```
public class Cat {
private String name;
private double weight;
private int age;
private String furColor;
private String breed;
public Cat(String name, double weight, int age, String furColor, String breed) {
this.name = name;
this.weight = weight;
this.age = age;
this.furColor = furColor;
this.breed = breed;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
public void play() {
System.out.println(name + " is playing.");
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFurColor() {
return furColor;
}
public void setFurColor(String furColor) {
this.furColor = furColor;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
```
在这个类中,我们定义了五个数据成员:名称、体重、年龄、毛色和属种。我们还定义了三个成员方法:吃东西、睡觉和玩东西。这些方法在被调用时会打印出相应的信息。
我们还提供了各成员变量的getter和setter方法,以便在外部访问和修改这些变量的值。
我们可以使用以下代码创建一个Cat对象,并调用其方法:
```
Cat myCat = new Cat("Whiskers", 3.5, 2, "gray", "Siamese");
myCat.eat();
myCat.sleep();
myCat.play();
```
输出:
```
Whiskers is eating.
Whiskers is sleeping.
Whiskers is playing.
```
这表明我们成功创建了一个Cat对象,并调用了它的方法。