1.this调用当前类中的属性和方法;
class Book{ private String bName; private double bPrice; public Book(String bName,double bPrice){ /* 以下的代码中this.bName表示的是类中的bName属性,而后面的bName指的是 当前方法中的参数bName中的属性; */ this.bName=bName; this.bPrice=bPrice; //此时this加或者不加都代表本类中的方法; this.print(); } public static void print(){ System.out.println("这个是本类中的方法"); } public String getInfo(){ return "书名:" + this.bName + ",价格:" + this.bPrice; } } public class Test{ public static void main(String args[]){ Book book = new Book("java",17.2);//默认调用构造方法; System.out.println(book.getInfo()); } }
1.this表示构造方法;
class Emp{ private int empno; private String ename; private String job; private double sal; //下面定义四个构造方法; public Emp(int empno){ this.empno = empno; this.ename = "无名氏"; this.job = "无记录"; this.sal = 0; } public Emp(int empno, String ename){ this.empno = empno; this.ename = ename; this.job = "后勤"; this.sal = 800.0; } public Emp(int empno, String ename,String job){ this.empno = empno; this.ename = ename; this.job = job; this.sal = 1000.0; } public Emp(int empno,String ename,String job,double sal){ this.empno = empno; this.ename = ename; this.job = job; this.sal = sal; } public String toString(){ return "编号:" + this.empno + ",姓名:" + this.ename + ",工作:" + this.job + ",工资:" + this.sal; } } public class Test{ public static void main(String args[]){ Emp e_1 = new Emp(8888); Emp e_2 = new Emp(7856,"小明"); Emp e_3 = new Emp(7666,"小红","web开发"); Emp e_4 = new Emp(7399,"smith","后端开发",150000.00); System.out.println(e_1); System.out.println(e_2); System.out.println(e_3); System.out.println(e_4); } }
以上代买过于繁杂,我们可以通过this([参数],[参数],...)来对本类中的构造方法进行调用,但是在进行调用的时候应当保留一个构造方法不被其他构造方法调用,即保留一个出口
class Emp{ private int empno; private String ename; private String job; private double sal; //下面定义四个构造方法; public Emp(int empno){ this(empno,"无名氏","无记录",0); } public Emp(int empno, String ename){ this(empno,ename,"后勤",800.0); } public Emp(int empno, String ename,String job){ this(empno,ename,job,1000.0); } public Emp(int empno,String ename,String job,double sal){ //在此构造方法中保留出口 this.empno = empno; this.ename = ename; this.job = job; this.sal = sal; } public String toString(){ return "编号:" + this.empno + ",姓名:" + this.ename + ",工作:" + this.job + ",工资:" + this.sal; } } public class Test{ public static void main(String args[]){ Emp e_1 = new Emp(8888); Emp e_2 = new Emp(7856,"小明"); Emp e_3 = new Emp(7666,"小红","web开发"); Emp e_4 = new Emp(7399,"smith","后端开发",150000.00); System.out.println(e_1); System.out.println(e_2); System.out.println(e_3); System.out.println(e_4); } }
this表示当前对象(重要),
class Print{ public void prin(){ System.out.println("this = " + this); } } public class Test{ public static void main(String args[]){ Print p1 = new Print(); System.out.println(p1); p1.prin();// Print p2 = new Print(); System.out.println(p2); p2.prin();// } }
运行结果:
Print@15db9742 this = Print@15db9742 Print@6d06d69c this = Print@6d06d69c