Inheritance,Interface, Package
Inheritance,Interface, Package
, Package
Inheritance
Inheritance is one of the key features of OOP that allows us to create a
new class from an existing class.
Inheritance is an object-oriented programming concept in which one class
acquires the properties and behavior of another class.
It represents a parent-child relationship between two classes. This
parent-child relationship is also known as an IS-A relationship.
The new class that is created is known as subclass (child or derived class)
and the existing class from where the child class is derived is known
as superclass (parent or base class).
Need of Java Inheritance:
1. Code Reusability
2. Extensibility
3. Implantation of Method Overriding
4. Achieving Abstraction( Data abstraction is the process of hiding
certain details and showing only essential information to the user.)
How to achieve/implement inheritance in Java?
Output:-
Name=abc
Roll no=12
Marks=66
Multilevel Inheritance
It is a child and parent class relationship where one can inherit from a
derived class, thereby making this derived class the base class for the
new class.
The inheritance in which a base class is inherited to a derived class
and that derived class is further inherited to another derived class is
known as multi-level inheritance. Multilevel inheritance involves
multiple base classes.
class Student class Marks extends Student
{ {
String name="abc"; int m1=67;
int rollno=12; int m2=88;
void display() int m3=90;
{ void total()
{
System.out.println("Name="+name) display();
; System.out.println("Marks1=
System.out.println("Roll "+m1+"\t marks2="+m2+"\t
no="+rollno); Marks3="+m3);
} System.out.println("Total="+
} (m1+m2+m3));
}
}
class StudentDetails extends Marks
{
}
}
Output:-
Name=abc
Roll no=12
Marks1= 67 marks2=88 Marks3=90
Total=245
Hierarchical Inheritance
The inheritance in which only one base class and multiple derived
classes is known as hierarchical inheritance.
Hierarchical inheritance occurs when multiple subclasses inherit from
a single superclass. It allows multiple classes to share common
properties and behaviours defined in the superclass.
class shape { class Hierarchical {
float length, breadth, radius; public static void main(String[]
} args) {
class rect extends shape {
public rect(float l, float b) { rect o1 =new rect(2,5);
length = l; System.out.println("Area of
breadth = b; Rectangle :
} "+o1.rectangle_area());
float rectangle_area() {
return length * breadth; circle o2 =new circle(5);
} System.out.println("Area of
} Circle : "+ o2.circle_area());
class circle extends shape { }
public circle(float r) { }
radius = r; Output:-
} Area of Rectangle : 10.0
float circle_area() { Area of Circle : 78.5
return 3.14f * (radius *
radius);
}
}
Multiple Inheritance