继承和多态之间的区别 [英] Difference between inheritance and polymorphism
问题描述
我正在研究多态性。我无法确定Java中有关这两个功能的类比。
I was studying about polymorphism. I couldn't determine the analogy in Java about these two features.
假设 Animal
类是具有 Cat
和 Dog
作为其子类。我知道这是继承的一个例子。但不是 Cat
和 Dog
类, Animal
上课?
Let's say Animal
class is a concrete superclass with Cat
and Dog
as its subclasses. I know that this is a case of inheritance. But isn't Cat
and Dog
classes, polymorphs of Animal
class?
我很清楚Java中的接口。我无法理解为什么使用接口而不是具体类来解释多态。可能是创建界面的整个目的是创建多态,但我想知道为什么接口而不是具体的类?
I am well aware of interfaces in Java. I couldn't understand why interfaces are used instead of concrete classes to explain polymorphism. It could be that the whole purpose of creating interface is to create polymorphs but I want to know why interfaces and not concrete classes?
推荐答案
class Animal{
public void speak(){ System.out.println("Speaking something");}
}
class Person extends Animal{
@Override
public void speak(){ System.out.println("Hello..");}
}
Animal a = new Person();
a.speak();// Hello
多态性的字典定义是指
生物学中的一个原则,其中有机体或物种可以有许多不同的形式
或阶段。这个原则也可以应用于面向对象的
编程和Java语言之类的语言。
类的子类可以定义它们自己的唯一行为,但是共享一些
与父类相同的功能 [..]
为何选择界面?
您知道需要做什么,但您希望实施者决定如何做,你将让实施者强有力地实施这些东西
You know what needs to be done, but you want implementers to decide how to do it, You will let implementer implement the stuffs forcefully
- when-best-to-use-an-interface-in-java
这篇关于继承和多态之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!