this引用

来源:互联网 发布:关口知宏结婚 编辑:程序博客网 时间:2024/05/16 12:00

this作为一个Java关键字,有两个作用:

n 代表隐含参数的调用

n 调用本类的其它的构造器

关键字this是用来指向当前对象(类实例)的。这里,this.name指的是当前对象的name字段。

例1

public class Person {

private double height = 1.75;

private double weight = 65;

private String name;

public Person(String aName) {

this.name = aName;// 全称应该是:Person.this.name

}

public Person() {

}

}

例2

public class Person {

private double height = 1.75;

private double weight = 65;

private String name;

public Person(String aName) {

this.name = aName;// 全称应该是:Person.this.name

}

public Person(){

this(“zhangsan”);

}

}

3

class Lamp {

int watts = 60;

boolean isOn = false;//属性声明

Lamp(boolean startOn) {

isOn = startOn;//这里isOn是上面声明的属性

}

public void setIsOn(boolean isOn) {

for (int dummy = 1; dummy < 1000; dummy++) {

System.out.println("The count is " + dummy);

}

this.isOn = isOn;//注意参数和属性名称相同,必须用this关键字来区分不同作用域

}

}

下面的代码用于调用上面的代码

Lamp aLamp = new Lamp();

aLamp.setIsOn(true);


原创粉丝点击