this
- 当前对象的默认引用。
- 可以调用对象的示例变量、实例方法、构造方法(调用构造方法时必须在重载方法内部,且必须是第一行)。
- 不能调用类变量和类方法(即static修饰的方法和变量),也不能调用局部变量。
this指向当前对象
public class Apple {
int a;
Apple eatApple(){
a++;
return this;
}
public static void main(String[] args) {
Apple apple = new Apple();
apple.eatApple().eatApple().eatApple();
}
}
this.xxx属性,表示当前类的属性
区别类中的num和参数num;
public class Apple {
private int num;
public Apple(int num){
this.num = num;
}
}
this 作用于构造函数
public class Apple {
private int num;
private String color;
public Apple(int num){
//this 必须在第一行,否则不能编译通过
this(num,"red");
}
public Apple(String color){
this(1,color);
}
public Apple(int num,String color){
this.num = num;
this.color = color;
}
}
this 必须在第一行,否则不能编译通过
super
- 代表对象的直接父类的默认引用
public class Apple extends Fruit{
@Override
public void eat() {
super.num = 5;
System.out.println("eat apple");
}
}
class Fruit{
public int num;
private String color;
public void eat(){
System.out.println("eat fruit");
}
}
下面示例报错的原因:父类color属性是私有的
修改后就不报错了
this super区别
关键字 | this | super |
---|---|---|
调用方式 | 本类的属性、构造函数、实例方法 | 父类的属性、构造函数、实例方法 |
调用位置 | 构造函数调用,必须第一行;其他无要求 | 构造函数调用,必须第一行;其他无要求 |
调用次数 | 一个构造函数调用一次 | 一个构造函数调用一次 |
super、this 出现在方法中注意事项
- super 代表当前对象直接父类对象的默认引用
- this 代表当前对象的默认引用
- super、this 出现在构造方法中,只能是构造方法的第一行,且不能同时出现
- 在类方法(即static修饰的方法)中不允许出现this、super关键字
- 在实例方法中 this super 不要求是第一行,且可以共存。