this就是这代带钱对象的 比如在构造函数中用的比较多 class Person{ private double height; private int age; public Person(double h, int a){ this.height = h; this.age = a; } }也就是说当你实例化Person的时候,会调用它的构造函数 Person p = new Person(1.85, 24);这句代码的潜台词就是p的升高是1.85,年龄是24岁 this就是p 懂了吗?
我给你一个例子你就可以懂起了 class TestThis{ int x=2; public void A(int x){ x=1; } public static void main(String args[]){ TestThis tt=new TestThis(); tt.A(3); System.out.println("x="+tt.x); } }没有使用this的时候,程序运行输出: x=2当你的A方法是 public void A(int x){ this.x=1; } 的时候,再运行程序,输出结果为: x=1
........1楼那个....java是现象对象语言 任何的方法和属性使用都要使用: 对象.属性 对象.方法()的格式而自己要使用自己的方法的时候,应该怎么办? 于是java就加入了一个this特殊变量来反向保存自己的实例 public class Test { public void isSame(Test ts) { System.out.println(this==ts); } public static void main(String[] args) { Test ts=new Test(); Test ts2=new Test(); ts.isSame(ts); ts.isSame(ts2); } }打印 true false
class Person{
private double height;
private int age; public Person(double h, int a){
this.height = h;
this.age = a;
}
}也就是说当你实例化Person的时候,会调用它的构造函数
Person p = new Person(1.85, 24);这句代码的潜台词就是p的升高是1.85,年龄是24岁 this就是p 懂了吗?
this的用法:
一)用在member方法里:
this.成员属性/方法 //这时this指的是"本对象"的,此时this操作的属性和方法都是对象里的东西。
this.static属性/方法 //这时this指的是"本类"的,此时this操作的属性和方法都是类的即带static。
二)this不能用在static方法里,比如main()方法里。不然javac时就会提示有错误。
(this可以去.static属性/方法,但不能用在static方法里)因此this常用在构造方法里,比如一个Hello.java
1:public class Hello{
2: private int x;
3: public Hello(int x){
4: this.x = x;
5: System.out.println(x);
6: System.out.println(this.x);
7: }
8:}
这里面this.x = x; 等号前面的x就是属性里的x,等号后面的x就是入参x,如果不加this,那么就成了x=x,两个x都是入参x.
this的还有个用法是用在<JavaBean 技术>里 通过this.get()/set()方法使用隐藏属性,这点你现在不用知道。
class TestThis{
int x=2;
public void A(int x){
x=1;
}
public static void main(String args[]){
TestThis tt=new TestThis();
tt.A(3);
System.out.println("x="+tt.x);
}
}没有使用this的时候,程序运行输出:
x=2当你的A方法是
public void A(int x){
this.x=1;
}
的时候,再运行程序,输出结果为:
x=1
任何的方法和属性使用都要使用:
对象.属性
对象.方法()的格式而自己要使用自己的方法的时候,应该怎么办?
于是java就加入了一个this特殊变量来反向保存自己的实例
public class Test
{
public void isSame(Test ts)
{
System.out.println(this==ts);
}
public static void main(String[] args)
{
Test ts=new Test();
Test ts2=new Test();
ts.isSame(ts);
ts.isSame(ts2);
}
}打印 true false
– 构造器中指该构造器所创建的新对象
– 方法中指调用该方法的对象
• this关键字的用法
– 在类本身的方法或构造器中引用该类的实例变量和方法
– 将当前对象作为参数传递给其它方法或构造器
– 用来调用其他的重载的构造器