java this的意义

来源:百度知道 编辑:UC知道 时间:2024/07/04 22:01:10
用this 的意义是什么?起到什么作用?
一般什么情况才会用上?为什么要用?

用this 的意义是什么?起到什么作用?
一般什么情况才会用上?为什么要用?

this代表当前对象,当前对象不懂?你只能把this写在一个类里边吧?这个放this的类的对象可以说是当前对象
public class Person{
String test = "";
public void print(){
System.out.print(this.test); //这个this就代表Person的对象,相当于 Person ps = new Person(); this.test 跟
//ps.test是一个玩意
}
}
作用就是你在某个类如我们自己写的Person类中用东西的时候你懒的写 Person ps = new Person(); 然后用ps调用,比较麻烦吧.
所以你直接用this代替就可以了
以上不用this版:
public class Person{
String test = "";
Person ps = new Person();
public void print(){
System.out.print(ps.test);
}
}
其实用不用它关系不大.不过一般都要用它,方便.它指向当前对象,所以不需要声明(Person ps = new Person();)就可以直接用此
对象,比较爽吧.
它还可以用全局变量和方法,还可以充当当前对象.
如下:
public class Person{
String test = ""; //A

public void print(){
System.out.print(ps.test);
}

public void test(String te