继承和多态的区别

本教程将介绍继承和多态的区别的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

继承和多态的区别 教程 第1张

问题描述

我正在研究多态性.我无法确定 Java 中关于这两个特性的类比.

假设 Animal 类是一个具体的超类,其中 CatDog 作为其子类.我知道这是一个继承的例子.但是 CatDog 类不是 Animal 类的变形吗?

我非常了解 Java 中的接口.我不明白为什么使用接口而不是具体的类来解释多态性.可能创建接口的全部目的是创建多态,但我想知道为什么是接口而不是具体类?

解决方案

继承

动物类{public void speak(){ System.out.println("说点什么");}}类人扩展动物{@覆盖public void speak(){ System.out.println("Hello..");}}

多态

Animal a = new Person();a.speak();//你好

多态性的字典定义是指一个原则生物体或物种可以有许多不同形式的生物学或阶段.这个原则也可以应用于面向对象编程和语言,如 Java 语言.a 的子类类可以定义自己独特的行为,但共享一些父类的相同功能 [..]

为什么选择接口?

你知道需要做什么,但你想让实施者决定怎么去做,你会让实施者强行实施这些东西

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

好了关于继承和多态的区别的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。