java定义一个丈夫Husband类,有姓名、年龄、妻子属性 定义一个妻子Wife类,有姓名、年龄、丈夫属性 丈夫类中有一个getInfo方法,其中,能显示自己的姓名,年龄,和他的妻子的姓名,年龄 妻子类中有一个getInfo方法,其中,能显示自己的姓名,年龄,和她的丈夫的姓名,年龄 定义一个测试类,创建妻子和丈夫对象,然后测试
时间: 2024-04-16 16:24:00 浏览: 137
java常用信息,有类及相关信息
你好!根据你的要求,我已经为你编写了相关的代码。请查看以下示例:
```java
class Husband {
private String name;
private int age;
private Wife wife;
public Husband(String name, int age, Wife wife) {
this.name = name;
this.age = age;
this.wife = wife;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Wife getWife() {
return wife;
}
public void getInfo() {
System.out.println("Husband: ");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Wife's Name: " + wife.getName());
System.out.println("Wife's Age: " + wife.getAge());
}
}
class Wife {
private String name;
private int age;
private Husband husband;
public Wife(String name, int age, Husband husband) {
this.name = name;
this.age = age;
this.husband = husband;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Husband getHusband() {
return husband;
}
public void getInfo() {
System.out.println("Wife: ");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Husband's Name: " + husband.getName());
System.out.println("Husband's Age: " + husband.getAge());
}
}
public class Test {
public static void main(String[] args) {
Husband husband = new Husband("John", 30, null);
Wife wife = new Wife("Jane", 28, husband);
husband = new Husband("John", 30, wife);
wife = new Wife("Jane", 28, husband);
husband.getInfo();
System.out.println();
wife.getInfo();
}
}
```
这段代码定义了一个Husband类和一个Wife类,它们之间通过相互引用来表示丈夫和妻子的关系。测试类Test创建了一个Husband对象和一个Wife对象,并测试了getInfo方法来显示他们的信息以及彼此的信息。
希望对你有所帮助!如有任何疑问,请随时提问。
阅读全文