Java定义一个哥哥brother类,有姓名年龄妹妹属性 定义一个妹妹sister类,有姓名,年龄.哥哥属性 哥哥类中有一个getinfo方法,其中,能显示自己的姓名,年龄和妹妹的姓名年龄妹妹类中有一个getinfo方法,其中,能显示自己的姓名,年龄和哥哥的姓名年龄定于一个测试类,创建妹妹和哥哥对象,然后测试
时间: 2023-09-13 22:08:24 浏览: 205
以下是Java代码实现:
```java
// 定义妹妹类
class Sister {
private String name;
private int age;
private Brother brother;
public Sister(String name, int age, Brother brother) {
this.name = name;
this.age = age;
this.brother = brother;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Brother getBrother() {
return brother;
}
public void getinfo() {
System.out.println("妹妹姓名:" + name);
System.out.println("妹妹年龄:" + age);
System.out.println("哥哥姓名:" + brother.getName());
System.out.println("哥哥年龄:" + brother.getAge());
}
}
// 定义哥哥类
class Brother {
private String name;
private int age;
private Sister sister;
public Brother(String name, int age, Sister sister) {
this.name = name;
this.age = age;
this.sister = sister;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Sister getSister() {
return sister;
}
public void getinfo() {
System.out.println("哥哥姓名:" + name);
System.out.println("哥哥年龄:" + age);
System.out.println("妹妹姓名:" + sister.getName());
System.out.println("妹妹年龄:" + sister.getAge());
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Sister sister = new Sister("小红", 10, null);
Brother brother = new Brother("小明", 20, sister);
sister = new Sister("小芳", 8, brother);
brother.getinfo();
System.out.println("--------------------");
sister.getinfo();
}
}
```
运行结果如下:
```
哥哥姓名:小明
哥哥年龄:20
妹妹姓名:小芳
妹妹年龄:8
--------------------
妹妹姓名:小芳
妹妹年龄:8
哥哥姓名:小明
哥哥年龄:20
```
阅读全文