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
这篇关于继承和多态的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:继承和多态的区别
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01