this和super关键字常用来指代父类对象与子类对象的关键字。
this关键字:表示当前对象的引用
-
this:区分同名的成员变量和局部变量
还可以调用本类的其他的重载的构造方法 -
this(name)使用this调用其他方法必须位于该构造方法的第一条语句
-
this调用构造方法只能调用一次
-
this不仅可以用于构造方法中,也可以用于setter()和getter()方法中
-
this可以出现在实例方法和构造方法中,但不可以出现在static方法中。
-
在普通方法中,调用其他方法时,this可以省略,加上this主要是增强代码的可读性
public class MyDate {
private int day, month, year;
public void tomorrow() {
this.day = this.day + 1; //this.day指的是当前对象的day字段
}
}
class Demothis{
int a; //成员变量
public Demo(int a) //在成员方法定义时,我们使用的形式参数与成员变量名称相同,这时我们要用到this
{
this.a = a;
}
}
super关键字:表示子类对象的父类引用
-
super可用于访问父类中定义的属性
-
super可用于调用父类中定义的成员方法
-
super可用于在子类构造器中调用父类的构造器
-
当子父类出现同名成员时,可以用super表明调用的是父类中的成员
-
super的追溯不仅限于直接父类
-
super和this的用法相像,this代表本类对象的引用,super代表父类的内存空间的标识
class Father
{
int x=0;
}
class Child extends Father{
int x=1;
Child() {
System.out.println (super.x);}
public static void main(String args[]){
new Child(); //super.x=0
}
}
子类的构造方法中,通过super关键字调用父类的构造方法
public class Student extends Person {
public Student(String myName, int myAge) {
super(myName, myAge);
}
}
方法覆盖后,通过super关键字调用父类的方法
public class Student extends Person {
public void showInfo(){
super.showInfo();
System.out.println(“,你的英语成绩是:”+engScore+”, JAVA成绩是:”+javaScore”);
}
}