申明一个Dog的类,包括成员变量姓名和年龄,构造函数,在主类中实例化一个Dog的数组有3只狗,(xiaobai,1)(xiaohei,2)(xiaohua,2),配合for循环打印3只小狗的名字和年龄
时间: 2024-05-09 17:14:23 浏览: 142
以下是Java语言的示例代码:
```java
public class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
Dog[] dogs = {new Dog("xiaobai", 1), new Dog("xiaohei", 2), new Dog("xiaohua", 2)};
for (Dog dog : dogs) {
System.out.println("Name: " + dog.getName() + ", Age: " + dog.getAge());
}
}
}
```
输出结果:
```
Name: xiaobai, Age: 1
Name: xiaohei, Age: 2
Name: xiaohua, Age: 2
```
阅读全文