赞
踩
当使用构造方法对成员变量进行初试化时,当局部变量与成员变量名称相同时,可能会出现命名冲突问题,这时候我们可以通过关键字this来解决这个问题。
关键字this表示当前类,有以下三种用法:
(1)表示类中成员;
(2)使用this调用构造方法;
(3)表示当前对象。
一、this表示类的成员
this.成员 //使用方法
此处类的成员既可以是成员变量,也可以是成员方法。
二、this调用构造方法
this(参数列表) //调用形式
注意:
(1)在非构造方法中不能使用this()调用。
(2)在构造方法中调用this(),调用的必须要是该构造方法的第一条语句。
三、this表示当前对象
直接使用this关键字,表示当前对象(此时this的值也是当前对象的首地址)。
四、实例
public class BookUse{ private string name; private double price; public void BookUse(){ name=""; price=0.0; System.out.println("construct1"); } public void BookUse(String name){ this.name=name; //this表示类的成员变量name System.out.println("construct2"); } public void BookUse(String name,double price){ this(name); //this调用带参构造函数 this.price=price; //this表示成员变量price System.out.prinitln("construct3"); } public void getBook(){ System.out.println("book's name is:"+name); System.out.println("book's price is:"+price); System.out.println("Book "+this);//this表示当前对象 } } class Book{ public static void main(String args[]){ BookUse b1 = new BookUse("《爱丽丝漫游仙境》",13.14); BookUse b2 = new BookUse("《绿野仙踪》",15.28); System.out.println(b1);//b1为当前对象 b1.getBook(); System.out.println(b2);//b2为当前对象 b2.getBook(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。