Java Reference
In-Depth Information
between humans for inheritance to occur. Similarly, there exists a relationship between objects of the superclass and
the subclass. The relationship that must exist between the superclass and the subclass in order for inheritance to be
effective is called an “is-a” relationship. You need to ask yourself a simple question before you should inherit a class
Q from a class P: “Is an object of class P also an object of class Q ?” If the answer is yes, class Q may inherit from class P .
Let's consider three classes Planet , Employee , and Manager . Let's ask the same question using these three classes
one-by-one.
Is a planet an employee? That is, does an “is-a” relationship exist between a planet and an
employee? The answer is no. Is an employee a planet? The answer is no.
Is a planet a manager? The answer is no. Is a manager a planet? The answer is no.
Is an employee a manager? The answer is maybe. An employee may be a manager, a clerk,
a programmer, or any other type of employee. However, an employee is not necessarily always
a manager. Is a manager an employee? The answer is yes.
You asked six questions using the three classes. You got “yes” as the answer in only one case. This is the only case
that is fit for using inheritance. The Manager class should inherit from the Employee class.
How does a class inherit another class? It is very simple to inherit a class from another class. You need to use the
keyword extends followed by the superclass name in the class declaration of your subclass. The general syntax is
<<class modifiers>>class <<SubclassName>> extends <<SuperclassName>> {
// Code for the Subclass goes here
}
For example, the following code declares a class Q , which inherits from class P :
public class Q extends P {
// Code for class Q goes here
}
You can use either the simple name or the fully qualified name of the superclass in a class declaration. If the
subclass and the superclass do not reside in the same package, you may need to import the superclass name to use
its simple name in the extends clause. Suppose the fully qualified names of class P and Q are pkg1.P and pkg2.Q ,
respectively. The above declaration may be rewritten in one of the following two ways: using simple name of the
superclass or using the fully qualified name of the superclass.
// #1 - Use the simple name of P in the extends clause and use an import statement.
package pkg2;
import pkg1.P;
public class Q extends P {
// Code for class Q goes here
}
// #2 - Use the fully qualified name of P. No need to use an import statement.
package pkg2;
public class Q extends pkg1.P {
// Code for class Q goes here
}
 
Search WWH ::




Custom Search