e.g://B.java
class A
{int x=2;
A(int y){x=y;}//等价于this.x=y
void f(A c)
{System.out.println("this.x="+this.x+"c.x="+c.x);}
}
class B
{public static void main(String args[])
{A a=new A(3);//a.x=3
A b=new A(4);//b.x=4
a.f(b);//this.x=3c.x=4
}}
使用this解决局部变量与成员变量同名的问题
局部变量(方法里);成员变量(类中方法外)
在成员变量前面加this,以此来区别局部变量,可以改变它的可见性
this.成员变量
//B.java
class A
{int x=2;
void f(int x){this.x=x;}
void g(int x){x=this.x;}
void s(){System.out.println(x);}
}
class B
{public static void main(String args[])
{A a=new A();//a.x=2
a.f(3);//a.x=3
a.s();//3
a.g(4);//a.x=3
a.s();//3
}}
e.g:class A
{int x=2;
void f(){x=3;int x=4;x=5;}
void s(){System.out.println(x);}
}
class B
{public static void main(String args[])
{A a=new A();//a.x=2
a.f();//a.x=3
a.s();//3
}}
用this调用本类另一个构造方法
常用于重载的构造方法之间的相互调用
this调用语句必须是构造方法中的第一个可执行语句
this(参数值表)
e.g:
class A
{int x=2;
A(int y){x=y;}
A(){this(3);}
A(int m,int n){this(m+n);}
void f(){System.out.println(x);}
}
class B
{public static void main(String args[])
{A a=new A();//a.x=3
a.f();//3
A b=new A(4,5);//b.x=9
b.f();//9
}}
this作方法的返回值或方法的实在参数时,代表当前对象
e.g:
public class A
{private int n=0;
A f(){n++;return this;}
void s(){System.out.println(n);}
public static void main(String args[])
{A a=new A();//a.n=0
a.f().f().f().s();//3
}}
e.g:
class A
{int n=2;
void f(A c){c.n=3;}
void s(){f(this);System.out.println(n);}
}
class B
{public static void main(String args[])
{A a=new A();//a.n=2
a.s();//3
}}
super
静态方法中不能使用super
表示当前对象的直接父类对象,是当前对象的直接父类对象的引用
不能在程序中显式修改它或给它赋值
用super标记是当前对象访问它从父类继承来的成员
super.父类成员变量名
super.父类成员方法名(参数值)
e.g: