当前位置:   article > 正文

Java this关键字_java中的`this`关键字表示当前类的实例

java中的`this`关键字表示当前类的实例

java的this关键字

当使用构造方法对成员变量进行初试化时,当局部变量与成员变量名称相同时,可能会出现命名冲突问题,这时候我们可以通过关键字this来解决这个问题。
关键字this表示当前类,有以下三种用法:
(1)表示类中成员;
(2)使用this调用构造方法;
(3)表示当前对象。
一、this表示类的成员

this.成员			//使用方法
  • 1

此处类的成员既可以是成员变量,也可以是成员方法。

二、this调用构造方法

this(参数列表)			//调用形式
  • 1

注意:
(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();
	}
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/563237
推荐阅读
相关标签
  

闽ICP备14008679号