gpt4 book ai didi

java - 接口(interface)/抽象类

转载 作者:行者123 更新时间:2023-12-02 00:46:52 25 4
gpt4 key购买 nike

我从某处读过一些行,但我无法清楚地理解这行的含义..我不知道为什么我无法理解。我非常清楚这两者之间的区别..但是请帮助我..并解释它的含义...?

In design, you want the base class to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behaviour), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. If anyone tries to make an object of an abstract class, the compiler prevents it.

提前致谢......

最佳答案

public abstract class Animal {
public abstract String speak();
}
public class Dog extends Animal {
public String speak() { return "woof!"; }
}
public class Duck extends Animal {
public String speak() { return "quack!"; }
}

Animal a = Zoo.getRandomAnimal();
a.speak();

您希望人们将动物称为“动物”,而不是特指“狗”或“鸭子”。这样,如果你培育出狗/鸭的杂交品种,从而创造出一种新型动物,它们就不必四处更改代码来应对这种新的奇迹。

他们在您的引文中谈到的接口(interface)并不是在谈论 Java“接口(interface)”,而是“您可以用来与该对象交互的方法的集合”。

所有动物都会说话,这才是重要的。这是界面。他们所说的到底是一个实现细节。

关于java - 接口(interface)/抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4746379/

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