可以使用成分而不是继承来实现Polymorphysim吗? (在Java中)

可以使用成分而不是继承来实现Polymorphysim吗? (在Java中)

问题描述:

我正在学习Java,我知道什么是继承和组合,我看到了很多使用继承的polymorphysim示例,所以我的第一个问题是,使用组合可以完成吗?如果是的话,请用一个小例子来表示。

I am learning Java, I know what inheritance and composition is, I saw numerous examples of polymorphysim showed using inheritance, so my first question is,can same be done using composition? If yes, please show with a small example.

我的第二个问题是,是否可以说polymorpysim基本上是方法重载和/或方法覆盖?如果是,那么为什么?

My second question is, can it be said that polymorpysim is basically method overloading and/or is method overiding ? if yes, then why ?

第一个问题



多态性可以可以通过两种方式在Java中实现:

First question

Polymorphism can be achieved in Java in two ways:


  • 通过类继承类A扩展B

  • 通过接口实现 A类实现C

  • Through class inheritance: class A extends B
  • Through interface implementation: class A implements C.

在后一种情况下,要正确实现A的行为,可以通过组合来完成,使A代表完成其他一些类/ es执行接口C中指定的任务。

In the later case, to properly implement A's behaviour, it can be done though composition, making A delegate over some other class/es which do the tasks specified in Interface C.

示例:假设我们已经有一些类imeplementing接口C:

Example: Let's suppose we have already some class imeplementing interface C:

class X implements C
{
    public String getName() {...}
    public int getAge() {...}
}

我们如何创建一个实现具有相同行为的C的新类X?像这样:

How can we create a new class implementing C with the same behaviour of X? Like this:

class A implements C
{
    private C x=new X();
    public String getName() {return x.getName();}
    public int getAge() {return x.getAge();}
} 



第二个问题



不,多态不是方法重载和/或方法重写(实际上,重载与面向对象设计无关):

Second question

No, polymorphism is not method overloading and/or method overriding (in fact, overloading has nothing to do with Object Oriented Design):


  • 方法重载包括创建一个新的与同一类中的某些其他(可能是继承的)方法具有相同名称但具有不同签名(=参数编号或类型)的方法。添加新方法是可以的,但这不是多态的目的。

  • 方法重写包括将新主体设置为继承方法,以便这个新方法body将在当前类中执行,而不是在继承方法的主体中执行。这是多态的一个优点,它仍然不是它的基础。

  • Method overloading consists on creating a new method with the same name that some other (maybe inherited) method in the same class but with a different signature (=parameter numbers or types). Adding new methods is OK, but that is not the aim of polymorphism.
  • Method overriding consists on setting a new body to an inherited method, so that this new body will be executed in the current class instead of the inherited method's body. This is a advantage of polymorphism, still is not the base of it either.

多态,简而言之,就是一个类的能力将用作作为不同的类/接口。

Polymorphism, in brief, is the ability of a class to be used as different classes/interfaces.