课堂多样性的现实生活实例

时间:2014-12-04 11:44:09

标签: oop polymorphism

我的老师让我在课堂上举例说明polymorphism。 我告诉他你是多态性的最佳例子。在大学里你是老师,在家里你是丈夫或父亲。所以你是一种方法,但在不同的状态下,你的行为也是如此。而且你也在扩展人类,所以你可以像人一样被多态化。

(考虑到多态性的定义:Acquiring more than one form

它可以被视为polymorphism的好例子吗?

感谢。

1 个答案:

答案 0 :(得分:1)

在您的示例中,您为不同的状态提供不同的行为。

在OOP中,这是通过接口表达的。

所以,它的建模方式如下:

class Human
{ 
    Date Birthdate;
}

interface ITeacher
{
    void Teach();
}

interface IHusband
{
    void Pray();
}

interface IFather
{
    void Love();    // methods in IFather and IHusband can be interchanged
}

class Person extends Human implements ITeacher, IHusband, IFather
{
   // implementations inserted here
}

现在你可以使用这些行为以及他在不同情况下是人的事实。

像:

 Human yourTeacher = new Human("1970/05/01");

 Class class = new Class();
 class.Teachers.Add(yourTeacher); // expecting that it is a collection of ITeachers.

 Pub pub = new Pub();
 pub.DrunkPeople.Add(yourTeacher); // accepting only humans older than 21 here

因此,多态性是关于 ONE 对象,在不同的情况下表现不同......和继承。

相关问题