在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
}
}