rithik
rithik

Reputation: 778

what is the difference between doing a class as subclass by inheritance and composition

what is the difference between doing a class as subclass by inheritance and composition

Upvotes: 1

Views: 216

Answers (2)

MHC
MHC

Reputation: 6405

Composition : the new class has the original class as an instance variable. The interface of the new class starts from the scratch. Only the properties and methods that the new class defines are available to the users of the class. The new class internally uses the old class object.

Subclass : the new class has all the properties and methods it's superclass defines. Any users can use the properties and methods. If the new class does not override them, the superclass implementation is automatically called. The subclass may add new properties or methods.

Usually subclassing is more helpful, but some cases composition can be helpful ( for example when working with class clusters).

Upvotes: 3

Related Questions