Professional Documents
Culture Documents
WHAT IS INHERITANCE?
ability of objects in java to inherit properties
and methods from other objects
A
parent, superclass,
base class
child, subclass,
B
derive class
ADVANTAGES OF INHERITANCE
1. Reuse of classes that have already been written
2. Grouping of related classes
3. Enhanced understandability and readability by
allowing classes to be arranged in a logical
manner
WHEN TO USE INHERITANCE
is-a rule
Example:
a. class Student & class UndergraduateStudent
b. class Employee & class Faculty
c. class Shape & class Circle
INSIDE INHERENCE
Keyword extends
class Shape{ class that is being inherited
}
class Circle extends Shape{
}
class Demo {
public static void main (String args[]) {
GraduateStudent gs = new GraduateStudent();
gs.display();
}
}
THE SUPERCLASS CAN BE INSTANTIATED
class Student {
private int studentID;
Student () {
studentID = 12345;
}
protected void display(){
System.out.println(“Student ID:” +studentID);
}
}
class GraduateStudent extends Student{
}
class Demo {
public static void main (String args[]) {
Student s = new Student( );
s.display();
}
}
CALLING CONSTRUCTORS
At least two constructors are involved
whenever a subclass inherits a superclass
CALLING CONSTRUCTORS
class Superclass{
Superclass(){
System.out.println(“superclass”);
}
}
class Subclass extends Superclass{
Subclass(){
System.out.println(“subclass”);
}
}
class Demo{
public static void main(String args[]){
Subclass s=new Subclass();
}
}
TYPES OF INHERITANCE
Simple or one way inheritance
Example
Student
GraduateStudent
TYPES OF INHERITANCE…CONT.
Multiple inheritance
Example
Person Student
GraduateStudent
TYPES OF INHERITANCE…CONT.
Multilevel inheritance
Example
Person
Student
GraduateStudent
Example
Person
Doctor Typist
Psychiatrist
example:
class Person{
final void warningMsg(){
System.out.println(“Invalid Entry.”);
}
}
FINAL KEYWORD…CONT.
3. it can be used to prevent a class from being
inherited
example:
final class Person{
void warningMsg(){
System.out.println(“Invalid Entry.”);
}
}
THE OBJECT CLASS AND SUBCLASSES
Object class – a master class that is
automatically inherited by all other classes,
including classes you define in your program
ABSTRACT CLASS
is a class that contains at least one abstract method
member
is a superclass that defines a general method member