Java Reference
In-Depth Information
Chapter 16
Inheritance
In this chapter, you will learn
What inheritance is
How to inherit a class from another class
The difference between early binding and late binding
What method overriding is and how to override methods
What field hiding and method hiding are and how to use them in your code
What abstract classes are and where to use them
final classes and methods
How to declare
The difference between “is-a,” “has-a,” and “part-of ” relationships
What is Inheritance?
Sometimes you may need the same functionality at multiple places in your application. There are different ways to
write code to achieve this. One way is to copy the same code in all places where you need the same functionality.
If you follow this logic, you need to make changes at all places when the functionality changes. Let's consider an
example where you need the same functionality at three different places. Suppose you have an application that deals
with three kinds of objects: planets, employees, and managers. Further, suppose that all three kinds of objects have
a name. You create three classes: Planet , Employee , and Manager to represent the three kinds of objects. Each class
has an instance variable called name and two methods called getName() and setName() . If you think about the code
in three classes to maintain the name of their objects, you would find that they are the same. You might have written
code for one class and copied it to other two classes. You may realize the problem in maintaining this kind of code
when the same code is copied multiple places. If you need to handle the name differently later, you will need to make
changes in three places. Inheritance is the feature of object-oriented programming that helps in such circumstances
to avoid copying the same code at multiple places, thus facilitating code reuse. Inheritance also lets you customize the
code without changing the existing code. Inheritance offers much more than just the code reuse and customization.
Inheritance is one of the cornerstones of object-oriented programming languages. It lets you create a new class
by reusing code from an existing class. The new class is called a subclass and the existing class is called the superclass.
A superclass contains the code that is reused and customized by the subclass. It is said that the subclass inherits
from the superclass. A superclass is also known as a base class or a parent class. A subclass is also known as a derived
class or a child class. Technically, it may be possible to inherit a class from any existing class. However, practically it
is not always a good idea to inherit a new class from any existing class. Inheritance in software development works
much the same way as inheritance in normal human life. You inherit something from your parents; your parents
inherit something from their parents, and so on. If you look at inheritance in human lives, there exists a relationship
 
Search WWH ::




Custom Search