super 与 this 关键字

super 与 this 关键字

this

顾名思义,this关键字指代的是当前对象的方法

super

意义为“超”,因为父类又叫超类,所以可以理解为当前类的父类的方法

举例

class Animal {
void eat() {
System.out.println("animal : eat");
}
}

class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void eatTest() {
this.eat(); // this 调用自己的方法
super.eat(); // super 调用父类方法
}
}

public class Test {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eatTest();
}
}

输出结果为
animal : eat
dog : eat
animal : eat

this调用的自己类的eat方法
super调用了自己类的父类的eat方法

posted @ 2022-08-16 20:35  FinallySSR  阅读(56)  评论(0)    收藏  举报