java this 子类调父类,父类再调用子类已覆盖的方法及属性(又一次理解)
时间: 2023-10-02 15:14:02 浏览: 66
在Java中,使用关键字 "this" 可以引用当前对象,而使用关键字 "super" 可以引用当前对象的父类对象。当子类继承父类时,子类可以覆盖父类的方法和属性,这意味着子类可以有自己的实现,并且可以屏蔽父类的实现。
如果子类需要调用父类的方法或属性,可以使用 "super" 关键字,如 "super.method()" 或 "super.property"。如果父类需要调用子类已覆盖的方法或属性,可以在子类中重写该方法或属性,并在父类中调用该方法或属性。
例如,假设有一个父类 Animal 和一个子类 Dog,Dog 覆盖了 Animal 的 eat() 方法和 weight 属性。可以在 Dog 的 eat() 方法中调用 Animal 的 eat() 方法,并在 Animal 的方法中调用子类的 weight 属性。
```
class Animal {
public void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
private int weight = 10;
public void eat() {
super.eat();
System.out.println("Dog is eating.");
}
public int getWeight() {
return weight;
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // 输出 "Animal is eating." 和 "Dog is eating."
System.out.println("Dog's weight is " + dog.getWeight()); // 输出 "Dog's weight is 10"
}
}
```
阅读全文
相关推荐
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)