Monday, February 14, 2011

What is inheritance?

Real objects often have a certain amount of common similarities with each other. For example there are many types of Bicycles: mountain bikes, road bikes, tandem bikes and so on. However all of these bicycles share similarities like: current speed, current pedal, cadence, current gear. Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. But, wouldn't it be great if we could just tell all our bikes to absorb sharing similarities and just worry about the new features the new bike will offer. Well, we can achieve this by using inheritance. (I won't write here about when to use inheritance, best practices, types of inheritance and so on. Hopefully, more on that in future posts, by now just the basic definition)

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:



With inheritance, programmers save time during program development by reusing proven and debugged high-quality software. This also increases the likelihood that a system will be implemented effectively.

When creating a class, rather than declaring completely new shared state and behaviors, you can designate that the new class should inherit them of an existing class. The existing class is called the superclass, and the new class is the subclass. (The C++ programming language refers to the superclass as the base class and the subclass as the derived class.) Each subclass can become the superclass for future subclasses.

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from

class MountainBike extends Bicycle {

//new fields and methods defining a mountain bike would go here

}
In this example this gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

No comments:

Post a Comment