Polymorphism

Polymorphism means that a variable of a supertype can refer to a subtype object. The three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism. You have already learned the first two. This section introduces polymorphism.

First, let us define two useful terms: subtype and supertype. A class defines a type. A type defined by a subclass is called a subtype, and a type defined by its superclass is called a supertype. Therefore, you can say that Circle is a subtype of GeometricObject and GeometricObject is a supertype for Circle.

The inheritance relationship enables a subclass to inherit features from its superclass with additional new features. A subclass is a specialization of its superclass; every instance of a subclass is also an instance of its superclass, but not vice versa. For example, every circle
is a geometric object, but not every geometric object is a circle. Therefore, you can always pass an instance of a subclass to a parameter of its superclass type. Consider the code in program below:

The method displayObject (line 12) takes a parameter of the GeometricObject type. You can invoke displayObject by passing any instance of GeometricObject (e.g., new CircleFromSimpleGeometricObject(1, “red”, false) and new RectangleFromSimpleGeometricObject(1, 1, “black”, false) in lines 7–8). An object of a subclass can be used wherever its superclass object is used. This is commonly known as polymorphism (from a Greek word meaning “many forms”). In simple terms, polymorphism means that a variable of a supertype can refer to a subtype object.

原文链接:Polymorphism

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
It is by acts and not by ideas that people live.
行动是根本,想法锦上添花
评论 抢沙发

请登录后发表评论

    暂无评论内容