Java Class Inheritance
In this chapter you will learn:
Description
In Java the classes can inherit attributes and behavior from pre-existing classes. The pre-existing classes are called base classes, superclasses, or parent classes. The new classes are known as derived classes, subclasses, or child classes. The relationships of classes through inheritance form a hierarchy.
Example
Let's look at an example. Suppose we have a class called Employee. It defines first name, last name. Then we want to create a class called Programmer. Programmer would have first name and last name as well. Rather than defining the first name and last name again for Programmer we can let Programmer inherit from Employee. In this way the Programmer would have attributes and behavior from Employee.
To inherit a class, you can use the extends
keyword.
The following program creates a superclass called Base
and a subclass called Child
.
class Base {//w ww . java2 s . c o m
int i, j;
void showBase() {
System.out.println("i and j: " + i + " " + j);
}
}
class Child extends Base {
int k;
void showChild() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i + j + k));
}
}
public class Main {
public static void main(String args[]) {
Base superOb = new Base();
Child subOb = new Child();
superOb.i = 10;
superOb.showBase();
System.out.println();
subOb.i = 7;
subOb.showBase();
subOb.showChild();
System.out.println();
subOb.sum();
}
}
The output from this program is shown here:
The subclass Child
includes all of the members of its superclass.
The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
You can only have one superclass for any subclass. Java does not support the multiple inheritance. A class can be a superclass of itself.
Next chapter...
What you will learn in the next chapter:
- What is super keyword
- How to use super to call superclass constructors
- How to use super to reference members from parent class
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keywordJava Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files