介绍
在Java
继承中,super
关键字用于调用父类的属性和方法,而this
则用于调用子类自身的属性和方法,this
也可以省略不写
Java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
public class Test {
public static void main(String[] args) { Dog dog = new Dog(); dog.eatTest(); } }
class Animal {
String name = "Animal";
void eat() { System.out.println("动物吃饭"); } }
class Dog extends Animal {
String name = "Dog";
@Override void eat() { System.out.println("小狗吃饭"); }
void eatTest() { super.eat(); this.eat(); System.out.println(super.name); System.out.println(this.name); } }
|
结果