Monday, 1 October 2012

What is Inheritance in Java?

An important concept in object-oriented programming is inheritance. It provides a way for objects to define relationships with each other. As the name inheritance suggests an object is able to inherit characteristics from another object. In more concrete terms, an object is able to pass on its state and behaviors to its children. For inheritance to work the objects need to have characteristics in common with each other.
For example, let's say we make a class called "Human" that represents our physical characteristics. It's a generic class that could represent you, me or anyone in the world. Its state keeps track of things like number of legs, number of arms, and blood type. It has behaviors like eat, sleep, and walk. Human is good for getting an overall sense of what makes us all the same but it can't for instance tell me about gender differences. For that we'd need to make two new class types called "Man" and "Woman". The state and behaviors of these two classes will differ from each other in a lot of ways except for the ones that their inherit from Human.

Therefore inheritance allows us to encompass the parent class' state and behaviors into its child. The child class can then extend the state and behaviors to reflect the differences it represents. The most important aspect of this concept to remember is that the child class is a more specialized version of the parent.

No comments:

Post a Comment