package com.atguigu.exer4; public class Girl { private String name; private int age; public void marry(Boy boy){ if(boy.getAge()<18){ System.out.println(this.name+":"+boy.getName()+"你个小屁孩一边玩去"); }else if(boy.getAge()<25){ System.out.println(this.name+":"+boy.getName()+"咱们先恋爱吧"); }else{ System.out.println(this.name+":"+boy.getName()+"咱们结婚爱吧"); boy.marry(this); //this指代上边的girl } } public void compare(Girl girl){ if(this.getAge()> girl.getAge()){ System.out.println(girl.getName()+"比"+this.getName()+"漂亮"); }else if(this.getAge()< girl.getAge()){ System.out.println(this.getName()+"比"+girl.getName()+"漂亮"); }else{ System.out.println(this.getName()+"和"+girl.getName()+"都漂亮"); } } public Girl(String name, int age) { this.name = name; this.age = 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; } }
package com.atguigu.exer4; public class Boy { private String name; private int age; public Boy(String name, int age) { this.name = name; this.age = age; } public void marry(Girl girl){ this.shout(); //由于 是 boy.marry所有这里的this指代的boy System.out.println(this.name+":"+girl.getName()+"我要爱你一万年"); } public void shout(){ System.out.println(this.name+":我要结婚了"); } 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; } }
package com.atguigu.exer4; public class Test { public static void main(String[] args) { Boy boy = new Boy("小龙哥", 30); Girl girl = new Girl("苍老师", 18); girl.marry(boy); //girl调用的marry,因此marry方法中的this指代的是girl对象 System.out.println("--------------------------"); Girl girl2 = new Girl("志林姐", 20); girl.compare(girl2); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)