用Java.创建一个狗类,具有颜色,品种,年龄,吃奥里给。创建一个测试类调用属性和方法。
时间: 2023-11-29 13:05:25 浏览: 41
请看下面的Java代码实现:
```java
public class Dog {
private String color;
private String breed;
private int age;
public Dog(String color, String breed, int age) {
this.color = color;
this.breed = breed;
this.age = age;
}
public String getColor() {
return color;
}
public String getBreed() {
return breed;
}
public int getAge() {
return age;
}
public void eat(String food) {
System.out.println("The dog is eating " + food);
}
}
```
测试类代码如下:
```java
public class TestDog {
public static void main(String[] args) {
Dog myDog = new Dog("brown", "Labrador Retriever", 3);
System.out.println("My dog is a " + myDog.getBreed() + " and is " + myDog.getColor() + " with an age of " + myDog.getAge() + " years old.");
myDog.eat("Orijen");
}
}
```
执行测试类的输出结果如下:
```
My dog is a Labrador Retriever and is brown with an age of 3 years old.
The dog is eating Orijen
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)