gpt4 book ai didi

java - 关于在 Java 中覆盖的说明

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:41:47 25 4
gpt4 key购买 nike

以此为例:

class Animal{

public void move(){
System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){
System.out.println("Dogs can walk and run");
}
}

public class TestDog{

public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class
}
}

在调用 b.move() 时,方法“Dog 类下的 move()”是否覆盖了“Animal 类下的 move()”,因为 Dog 对象在调用同一方法时优先何时被 Animal 类型引用?

我注意到许多网站并没有解释这一点,而是只是抛出一些例子,而不是逐行讨论这些内容。只是想消除我的术语混淆。

旁注,是否可以有一个 Dog 对象但调用 Animal 类下的 move()?例如有这样的东西:

Dog doggy = new Dog();
doggy.move()
>>>
Animals can move
>>>

这可能吗? ((Animal) doggy).move() 会完成这个吗?

最佳答案

当然,调用 b.move() 方法“Dog 下的move()”是正确的覆盖了“Animal 类下的move()”。

对于第二个问题,你应该将 Dog 类实现为:

public class Dog extends Animal {

public void move(){
super.move();
}
}

对于第三个问题,答案是“NO”。

          ((Animal) doggy).move()

这只是“冗余”并给出输出“Dog 类下的move()”。

关于java - 关于在 Java 中覆盖的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36098976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com