Java this關鍵字的使用案例詳解

通過一個小案例來學習、理解一下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);
	}
}

運行結果

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: