欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java this关键字的使用案例详解

程序员文章站 2022-06-18 16:17:54
目录boy类girl类boygirltest类总结通过一个小案例来学习、理解一下this关键字的使用~~~boy类package myjava1;public class boy {private s...

通过一个小案例来学习、理解一下this关键字的使用~~~

Java 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);
	}
}

运行结果

Java this关键字的使用案例详解

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!