标签:
1. Java中this关键字代表对象本身。用this关键字可以在类的内部调用属性和方法,这样代码的可读性比较高,因为它明确的指出了这个属性或方法的来源。
2. 同时在构造函数中也可以使用this关键字调用本类中的其它构造函数,但有几点需要注意:
3. 一个类的构造函数分为无参和有参构造函数。通常做法是指定写好一个包含所有字段的构造函数,然后其它构造函数可以直接调用该函数,实现代码重用。
package org.lyk.entities; public class Emp implements Comparable<Emp> { private long empno; private String ename; private String job; private float sal; public long getEmpno() { return empno; } public void setEmpno(long empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public float getSal() { return sal; } public void setSal(float sal) { this.sal = sal; } @Override public String toString() { return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", sal=" + sal + "]"; } public Emp() { this(-1, "无名氏", "未指定", 0); } public Emp(long empno) { this(empno,"无名氏","未指定",0); } public Emp(long empno, String name) { this(empno, name, "未指定", 0); } public Emp(long empno, String ename, String job, float sal) { super(); this.empno = empno; this.ename = ename; this.job = job; this.sal = sal; } @Override public int compareTo(Emp o) { if(this.sal < o.sal) return -1; else if(this.sal > o.sal) return 1; if(this.empno < o.empno) return -1; else if(this.empno > o.empno) return 1; return 0; } }
package org.lyk.main; import org.lyk.entities.Emp; public class Main { public static void main(String[] args) { Emp[] emp = new Emp[4]; emp[0] = new Emp(); emp[1] = new Emp(9989); emp[2] = new Emp(9987,"Jerry"); emp[3] = new Emp(7786,"Larry","programer",889); java.util.Arrays.sort(emp); for(Emp item : emp) { System.out.println(item); } } }
标签:
原文地址:http://www.cnblogs.com/kuillldan/p/5899881.html