添加必要的构造器,综合应用构造器的重载,this关键字
Girl
-name:String
+setName(i:String)
+getName():String
+marry(boy:Boy)
Boy
-name:String
-age:int
+setName(i:String)
+getName():String
+setAge(i:int)
+getAge():int
+marry(girl:Girl)
+shout():void
Boy类
package test4;
public class Boy {
private String name;
private int age;
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 void marry(Girl girl) {
System.out.println("我要娶"+girl.getName());
}
public void shout() {
if(age>=22) {
System.out.println("我到了结婚的年龄");
}else {
System.out.println("还是先谈恋爱吧");
}
}
}
Girl类
package test4;
public class Girl {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public void marry(Boy boy) {
System.out.println("我要娶"+boy.getName());
boy.marry(this);
}
}
测试代码:
package test4;
public class test {
public static void main(String[] args) {
Boy boy = new Boy();
boy.setName("小明");
boy.setAge(23);
Girl girl = new Girl();
girl.setName("小花");
boy.marry(girl);
boy.shout();
System.out.println();
girl.marry(boy);
}
}
运行结果: