继承和多态的区别

2022-01-24 00:00:00 polymorphism interface java

我正在研究多态性.我无法确定 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 的子类类可以定义自己独特的行为,但共享一些父类的相同功能 [..]

<小时>

为什么选择接口?

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

  • 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

相关文章