编写一个D0g关,其中的私有成员包括,name ,color , age•请使用get. set方法访问私有交量。Dog类的无参构造方法,name=dog1,color= white.age=1。有参构造方法name colorage从健品上输入。请在主类中 创建dog1,用无登构造方法,dog2为有参构造方法。输出语句为:System.out printin(name=" t d1 getNameo + "color=” +d1. getcoloro+",age="+d1.getAge() 输入输出说明: 输入: peter red 6 输出: nane=dogl, coloriwhite, age-1 nane- peter, color=red, ag re=6 代码编辑: F
时间: 2024-03-06 11:49:43 浏览: 65
PHP使用方法重载实现动态创建属性的get和set方法
以下是实现了您要求的代码:
```java
public class Dog {
private String name;
private String color;
private int age;
public Dog() {
this.name = "dog1";
this.color = "white";
this.age = 1;
}
public Dog(String name, String color, int age) {
this.name = name;
this.color = color;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
在主类中创建对象并输出:
```java
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog("peter", "red", 6);
System.out.println("name=" + dog1.getName() + ", color=" + dog1.getColor() + ", age=" + dog1.getAge());
System.out.println("name=" + dog2.getName() + ", color=" + dog2.getColor() + ", age=" + dog2.getAge());
}
}
```
输出结果为:
```
name=dog1, color=white, age=1
name=peter, color=red, age=6
```
阅读全文