Difference between inheritance and polymorphism(继承和多态的区别)
问题描述
我正在研究多态性.我无法确定 Java 中关于这两个特性的类比.
假设 Animal
类是一个具体的超类,其中 Cat
和 Dog
作为其子类.我知道这是一个继承的例子.但是 Cat
和 Dog
类不是 Animal
类的变形吗?
我非常了解 Java 中的接口.我不明白为什么使用接口而不是具体的类来解释多态性.可能创建接口的全部目的是创建多态,但我想知道为什么是接口而不是具体类?
继承
动物类{public void speak(){ System.out.println("说点什么");}}类人扩展动物{@覆盖public void speak(){ System.out.println("Hello..");}}
<小时>
多态
Animal a = new Person();a.speak();//你好
<块引用>
多态性的字典定义是指一个原则生物体或物种可以有许多不同形式的生物学或阶段.这个原则也可以应用于面向对象编程和语言,如 Java 语言.a 的子类类可以定义自己独特的行为,但共享一些父类的相同功能 [..]
<小时>
为什么选择接口?
你知道需要做什么,但你想让实施者决定如何去做,你会让实施者强行实施这些东西
- when-best-to-use-an-interface-in-java
I was studying about polymorphism. I couldn't determine the analogy in Java about these two features.
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?
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?
Inheritance
class Animal{
public void speak(){ System.out.println("Speaking something");}
}
class Person extends Animal{
@Override
public void speak(){ System.out.println("Hello..");}
}
Polymorphism
Animal a = new Person();
a.speak();// Hello
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class [..]
Why Interface ?
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
这篇关于继承和多态的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:继承和多态的区别


- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01