java中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()只能用一个

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值