JAVA_SE基础——33.this关键字的练习

需求:使用java定义的一个人类,人具备 id ,name ,age 三个属性,还具备一个比较年龄的方法。

要求:必须要写上构造函数,构造函数也必须要使用上this关键字。


class Person{
	
	int id;//编号
	
	String name;//姓名
	
	int age;//年龄
	
	public Person(int id,String name,int age){ //构造函数
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	public void compareAge(Person p2){//比较年龄的函数
		 if(this.age>p2.age){//this表示p1
			 System.out.println(this.name+"比"+p2.name+"大");
		 }else if(this.age<p2.age){
			 System.out.println(p2.name+"比"+this.name+"大");
		 }else 
			 System.out.println("都是同龄人");
	}
	
}
public class Demo8 {
	public static void main(String[] args){//主方法入口
		Person p1 = new Person(110,"小明",18);//对象p1
		Person p2 = new Person(119,"小红",17);//对象p2
		p1.compareAge(p2);//把p2的值传入compareAge()函数中
	}
}



认真看过代码的都应该能接受吧。我比较菜,所以有些东西写的可能不太好,请多多包涵


原文地址:https://www.cnblogs.com/Jhaiha0/p/8465310.html