您的位置:首页 > 编程语言 > Java开发

java中的this

2016-02-11 22:55 429 查看

java中的this

this主要要三种用法:

1、表示对当前对象的引用。

2、表示用类的成员变量(而非函数参数)。

3、用于在构造方法中引用满足指定参数类型的构造方法。

注意:this不能用在static方法中。每当一个对象创建后,Java虚拟机会给这个对象分配一个引用自身的指针,这个指针的名字就是 this。因此,this只能在类中的非静态方法中使用,静态方法和静态的代码块中绝对不能出现this的用法。

这里this表示什么?

// 该例意在演示this的用法
public class MyDate {
private int day, month, year;
// 创建构造方法
public MyDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public String tommorrow() {
day = day +1;
return day + "/" + month + "/" + year;
}
public static void main(String[] args) {
MyDate d = new MyDate(11,2,2016);
System.out.println(d.tommorrow());
}
}
/*
* 12/2/2016
* */
```

如果在某个方法中把this作为返回值,则可以多次连续调用一个方法:
```java
public class ReturnThis {
int number;

ReturnThis increment() {
number++;
return this;
}

private void print() {
System.out.println("number = " + number);
}

public static void main(String[] args) {
ReturnThis tt = new ReturnThis();
tt.increment().increment().increment().increment().print();
}
}

<div class="se-preview-section-delimiter"></div>


体会下面的两个例子:

public class ThisDemo {
String name;
int age;

public ThisDemo() {
this.age = 21;
}

public ThisDemo(String name, int age) {
//this();
this.name = "Nick";
}

private void print() {
System.out.println("最终的名字 = " + this.name);
System.out.println("最终的年龄 = " + this.age);
}

public static void main(String[] args) {
ThisDemo tt = new ThisDemo("", 0); // 随便传进去的参数
tt.print();
}
}
/*
* 最终的名字 = Nick
最终的年龄 = 0
*/

<div class="se-preview-section-delimiter"></div>


public class ThisDemo {
String name;
int age;

public ThisDemo() {
this.age = 21;
}

public ThisDemo(String name, int age) {
this();
this.name = "Nick";
}

private void print() {
System.out.println("最终的名字 = " + this.name);
System.out.println("最终的年龄 = " + this.age);
}

public static void main(String[] args) {
ThisDemo tt = new ThisDemo("", 0); // 随便传进去的参数
tt.print();
}
}
/*
* 最终的名字 = Nick
最终的年龄 = 21
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: