class Leg {// 腿 private int length; public Leg(int length) { this.length = length; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } } class Head {// 头 private String type;// 类型 public Head(String type) { this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } } class Person { private String name;// 姓名 private char sex;// 性别 private Leg leg;//腿 private Head head;//头 public Person(String name) { this.name = name; } public Person(String name, char sex) { this(name); this.sex=sex; } public Leg getLeg() { return leg; } public void setLeg(Leg leg) { this.leg = leg; } public Head getHead() { return head; } public void setHead(Head head) { this.head = head; } public String getPerson() { StringBuffer sb=new StringBuffer(); sb.append(this.name+leg.getLength()+head.getType()); return sb.toString(); } } //测试类 public class DogDemo { public static void main(String[] args) { Leg leg=new Leg(30); Head head=new Head("123"); Person zhangfei=new Person("234",'女'); zhangfei.setLeg(leg); zhangfei.setHead(head); leg.setLength(80); System.out.println(zhangfei.getPerson()); } }
时间: 2024-02-14 20:04:17 浏览: 34
这段代码存在一些问题,其中`Person`类中的`getPerson()`方法中的字符串拼接不太合适,应该使用格式化字符串来实现。此外,`Person`类中的`sex`属性没有被使用。
以下是修改后的代码:
```
class Leg {
private int length;
public Leg(int length) {
this.length = length;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
}
class Head {
private String type;
public Head(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
class Person {
private String name;
private char sex;
private Leg leg;
private Head head;
public Person(String name) {
this.name = name;
}
public Person(String name, char sex) {
this(name);
this.sex = sex;
}
public Leg getLeg() {
return leg;
}
public void setLeg(Leg leg) {
this.leg = leg;
}
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
public String getPerson() {
return String.format("%s %d %s", name, leg.getLength(), head.getType());
}
}
public class DogDemo {
public static void main(String[] args) {
Leg leg = new Leg(30);
Head head = new Head("123");
Person zhangfei = new Person("234", '女');
zhangfei.setLeg(leg);
zhangfei.setHead(head);
leg.setLength(80);
System.out.println(zhangfei.getPerson());
}
}
```
输出结果为:
```
234 80 123
```