Java this关键字的使用
是一只派大鑫 人气:0通过一个小案例来学习、理解一下this关键字的使用~~~
Boy类
package myjava1; public class Boy { private String name; private int age; public Boy() { } public Boy(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; } public void marry(Girl girl) { System.out.println(this.name+ " 也想娶:" + girl.getName()); } public void shout() { if(this.age >= 22) { System.out.println("可以了"); }else { System.out.println("不可以"); } } }
Girl类
package myjava1; public class Girl { private String name; private int age; public Girl() { } 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; } public void marry(Boy boy) { System.out.println(this.name + " 想嫁给:" + boy.getName()); boy.marry(this); } public void compare(Girl girl) { if(this.age > girl.getAge()) { System.out.println(this.getName() + "比" + girl.getName() + "大"); }else if(this.age < girl.getAge()) { System.out.println(this.getName() + "比" + girl.getName() + "小"); }else { System.out.println(this.getName() + "和" + girl.getName() + "一样大"); } } }
BoyGirlTest类
package myjava1; public class BoyGirlTest { public static void main(String[] args) { Boy boy = new Boy("罗密欧",21); boy.shout(); Girl girl = new Girl("朱丽叶",18); girl.marry(boy); Girl girl2 = new Girl("祝英台",19); girl2.compare(girl); girl.compare(girl2); girl2.compare(girl2); } }
运行结果
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!
加载全部内容