The mechanism of creating a new class from an old one is called inheritance.
The old class is known as base class or super class or parent class.
The new class is known as subclass or derived class or child class.
Different forms of inheritance are:
Defining a Subclass:A
subclass can be defined as:
class subclassname
extends superclassname
{
variables declaration;
methods declaration;
}
The keyword extends signifies that the properties of the superclassname are
extended to the subclassname.
Example of
Single Inheritance:
class
Base{
int a,b;
Base(int x,int y) {
a=x;
b=y;
}
Base(){
a=0;
b=0;
}
void display() {
System.out.println("A : "+a+" B : "+b);
}
}
class
Derive extends Base{
int c;
Derive(int x,int y,int z) {
super(x,y);
c=z;
}
int sum(){
return (a+b+c);
}
}
class
Single{
public
static void main(String args[]) {
Derive d=new Derive(10,20,30);
int sum=d.sum();
d.display();
System.out.println("Sum : "+sum);
}
}
Output: A : 10 B : 20
Sum
: 60
Subclass
Constructor and Using super:
o A
subclass constructor is used to construct the instance variables of both the
subclass and the superclass.
o The
Subclass constructor uses the keyword super
to invoke the constructor method of the super class.
o During
the use of the keyword super, the
following conditions must be satisfied:
i.
super
may only be used within a subclass constructor method.
ii.
The call to superclass
constructor must appear as the first statement within the subclass constructor.
iii.
The parameters in the super call must match the order and
type of the instance variables declared in the superclass.
Example of Multilevel
Inheritance:
class
A
{
….
….
}
class
B extends A //First Level
{
….
….
}
class
C extends B //Second Level
{
….
….
}
Example of Hierarchical
Inheritance:
class
A
{
….
….
}
class
B extends A
{
….
….
}
class
C extends A
{
….
….
}
No comments:
Write comments