this和super的用法
this
this的作用
直接引用相当于指向当前对象本身
此情况下this可以省略
public class This02 {
public void A() {
System.out.println("我是A函数");
}
public void B() {
this.A();
System.out.println("我是B函数");
}
public static void main(String[] args) {
This02 this02 = new This02();
this02.B();
}
}
运行结果
我是A函数
我是B函数
当实例变量与局部变量重名时
this表示调用当前类的实例变量
public class This01 {
int i=0;//实例变量
public static void main(String[] args) {
This01 this01 = new This01();
this01.test1();
}
public void test1(){
int i= 2;//局部变量
System.out.println(i);
System.out.println(this.i);
}
}
运行结果
2
0
在构造器中使用
this可以调用当前对象的其他构造器
public class this03 {
int i=0;//实例变量
int j=1;
public static void main(String[] args) {
int a=1;
int b=2;
Fu fu = new Fu(1,2);
}
//无参构造器
public this03() {
System.out.println("我是无参构造器");
}
//有参构造器
public this03(int i,int j) {
this();//调用其他构造器
System.out.println("我是有参构造器");
}
}
运行结果
我是无参构造器
我是有参构造器
注意:this()必须写在首行
super
super作用
普通直接引用
与this相似,super.xx引用父类成员(最近的一个父类)
子类中的成员变量或方法与父类中的成员变量或方法同名
public class SuperTest {
int n = 1;
public void value() {
System.out.println("我是父类的value函数");
}
public static void main(String[] args) {
SuperTest01 superTest01 = new SuperTest01();
superTest01.value();
}
}
class SuperTest01 extends SuperTest{
public void value() {
int n = 2;
super.value();//引用父类成员函数
System.out.println("我是子类的value函数");
System.out.println(n);
System.out.println(super.n);//引用父类成员变量
}
}
运行结果
我是父类的value函数
我是子类的value函数
2
1
引用父类的构造函数
public class SuperZi extends SuperFu{
int a;
int b;
int c;
public SuperZi() {
super();//调用父类无参构造
System.out.println("我是子类无参构造函数");
}
public SuperZi(int a,int b,int c) {
super(a,b);//可以简化代码
this.c = c;
System.out.println("我是子类有参构造函数");
}
public static void main(String[] args) {
SuperZi superZi = new SuperZi();
SuperZi superZi2 = new SuperZi(1,2,3);
}
}
运行结果
我是父类的无参构造函数
我是子类无参构造函数
我是父类的有参构造函数
我是子类有参构造函数
注意:super()只能卸载首行,且super()和this()只能用一个