img
Inheritance
I
nheritance is one of the cornerstones of object-oriented programming because it allows
the creation of hierarchical classifications. Using inheritance, you can create a general
class that defines traits common to a set of related items. This class can then be inherited
by other, more specific classes, each adding those things that are unique to it. In the terminology
of Java, a class that is inherited is called a superclass. The class that does the inheriting is called
a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the
instance variables and methods defined by the superclass and adds its own, unique elements.
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by using
the extends keyword. To see how, let's begin with a short example. The following program
creates a superclass called A and a subclass called B. Notice how the keyword extends is
used to create a subclass of A.
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home