21 November 2011

When to Use Inheritance ?

When to Use Inheritance ?

Inheritance is a good choice when:
  • Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
  • You can reuse code from the base classes.
  • You need to apply the same class and methods to different data types.
  • The class hierarchy is reasonably shallow, and other developers are not likely to add many more levels.
  • You want to make global changes to derived classes by changing a base class.
  • Composition – Composition is used when the two class has-a relationship among classes
    Inheritance – Inheritance is used when the derived class is-a relationship base class

    For example :
    Take two class
    1.House owner

    House owner is a House is not valid - Inheritance
    House owner has a house is valid - Composition

    For example :
    Take two class

    Cricket is a game is valid - Inheritance
    Cricket has a game is invalid - Composition

No comments:

Post a Comment

Comments Welcome