Inheritance
Inheritance
Introduction
Inheritance is a mechanism that enables one
class to inherit all the behaviour and
attributes of another class.
Through inheritance, a class immediately
has all the functionality of an existing class.
Because of this, you must define only how
the new class is different from an existing
class.
Inheritance is one of the primary features of
OOP — which is a form of software reuse.
© K.S. Mbise Inheritance Slide 2
Introduction cont...
A class that is inherited is called superclass
The class that inherits is called subclass
A subclass is a specialized version of a
superclass
extends – (or “inherits from”) keyword is used
to inherit superclass
Java does not support multiple superclasses into
single subclass (this differs from C++)
A subclass can be a superclass of another
subclass
© K.S. Mbise Inheritance Slide 3
Inheritance example
//create superclass
public class A {
int x,y;
void showXY(){
System.out.println("x and y: "+x+ "
"+y);
}
}
© K.S. Mbise Inheritance Slide 4
Inheritance example
cont…
//create subclass by extending class A
class B extends A{
int z;
void showZ(){
System.out.println("k: "+z);
}
void sum(){
int sum=x+y+z;
System.out.println("sum: "+sum);
}
}