1、编程题
/*
1.定义一个丈夫Husband类,有姓名、年龄、妻子属性
定义一个妻子Wife类,有姓名、年龄、丈夫属性
丈夫类中有一个getInfo方法,其中,能显示自己的姓名,年龄,和他的妻子的姓名,年龄
妻子类中有一个getInfo方法,其中,能显示自己的姓名,年龄,和她的丈夫的姓名,年龄
定义一个测试类,创建妻子和丈夫对象,然后测试
*/
这一题,重点在于如何引用“类”属性,定义一个类,做为引用对象。引用位置:
//private Wife wife;
//private Husband husband;
输出时,注意输出方法时(引用数据的格式)格式为,变量名.get方法(例子:wife.getName())
public class Husband { private String name; private int age; private Wife wife;//类名+变量名 public Husband() { } public Husband(String name, int age, Wife wife) { this.name = name; this.age = age; this.wife = wife; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Wife getWife() {//注意返回类型 return wife; } public void setWife(Wife wife) {//注意形参 this.wife = wife; } public void getInfo() { System.out.println("丈夫的姓名为:" + name + ",年龄为:" + age + ",妻子属性,妻子姓名:" + wife.getName() + ",年龄:" + wife.getAge()); } }
public class Wife { private String name; private int age; private Husband husband;//类名+变量名 public Wife(){ } public Wife(String name,int age,Husband husband){ this.name=name; this.age=age; this.husband=husband; } public String getName(){ return name; } public void setName(String