java基础:面向对象(this和super的区别和应用)

在java的继承中,this与super的区别

分别是什么呢?

this代表对本类应用的引用;

super代表父类储存空间的标识,也可以说是对父类应用的引用。

怎么用呢?

A:调用成员变量(本篇代码例子主要记的)

this.成员变量       调用的是本类的成员变量;

super.成员变量 调用的是父类的成员变量。

B:调用构造方法(下一篇记)

this(...) 调用本类的构造方法;

super(...) 调用类的构造方法。

C:调用成员方法(后面记)

this.成员方法 调用的是本类的成员方法;

super.成员方法 调用的是父类的成员方法。


代码例子:

public class this与super的区别 {
public static void main(String[] args){
Son2 s = new Son2();
s.show();
System.out.println("---------------");
s.method();
}
}


class GrandFather2{ //Father2的父类
int num = 0;
}


class Father2 extends GrandFather2{ //son2父类,同时继承了GrandFather2
int num = 10;

public void show(){
int num = 20;
System.out.println(num); //就近原则,调用本方法中的变量,输出20
System.out.println(this.num); //this,调用本类中的成员变量,输出10
System.out.println(super.num); //super,调用父类GrendFather2的成员变量,输出0
}
}


class Son2 extends Father2{ //继承了Father2
int num = 30;

public void method(){
int num = 40;
System.out.println(num); //就近原则,调用本方法中的变量,输出40
System.out.println(this.num); //this,调用本类中的成员变量,输出30
System.out.println(super.num); //super,调用父类GrendFather2的成员变量,输出10
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值