this 关键字用于引用类的当前实例。 例如:
class Manager {
Employees[] employees;
void manageEmployees() {
int totalEmp = this.employees.length;
System.out.println("Total employees: " + totalEmp);
this.report();
}
void report() { }
}
在上面的示例中,this 关键字用于两个地方:
this 关键字是可选的,这意味着,上面的示例可以不显式使用此关键字,但是,使用此关键字可能会使代码更易读和易懂。
super 关键字用于从子类访问父类的变量和方法。例如:
public class Super {
protected int number;
protected showNumber() {
System.out.println("number = " + number);
}
}
public class Sub extends Super {
void bar() {
super.number = 10;
super.showNumber();
}
}
在上面的例子中,Sub 类访问父类成员变量 number ,并调用其父类 Super 的 showNumber()
方法。
** 使用 this 和 super 要注意的问题:**
super()
调用父类中的其他构造方法时,该语句必须处于构造器的首行,否则编译器会报错。另外,使用 this 调用本类中的其他构造方法时,也要放在首行因为被 static 修饰的成员属于当前类,不属于该类的某个对象,是被类中的所有对象共享。而 this 代表对本类对象的引用,指向本类对象;而 super 代表对父类对象的引用,指向父类对象;所以,this 和 super 都属于对象范畴,而静态方法是属于类范畴的东西。