class Student implements Comparable//该接口强制让学生具备比较性
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
if (!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s = (Student)obj;
System.out.println(this.name+"::compare to::"+s.name);
if (this.age > s.age)
return 1;
if(this.age == s.age)
{
return this.name.compareTo(s.name);
};
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
你在主类中new一个学生对象的时候,比如:Studuent stu = Student("zhangsan",20),对象一建立就有了属性和方法
构造函数中this.name = name,中的this代表的就是对象stu,this.name = name,实例化就是stu.name = "zhangsan"
public int compareTo(Object obj)这个方法,引用时就是stu.compareTo(obj),this关键字代表了当前对象,类中调用时很方便 |