Table of Contents
Inheritance in the java programming language
In this tutorial, we will discuss Inheritance In Java programming language
Knowledge Area
What is inheritance?
Type of Inheritance
extends and super keyword
Method overriding
Abstract Class & Methods
what is inheritance?
Inheritance is one of the feature or mechanism of Object-Oriented programming Languages(OOPs). Inheritance allows a class to use the properties or data members and methods of another class.so The derived class inherits or acquire the states and behaviours from the base class. The derived class is also called subclass and the base class also called superclass(parent class). it is a mechanism for code reuse and to allow independent extensions of the original software via public classes and interfaces.
Type of inheritance
Simple Inheritance
Multi-Level inheritance
extends keyword
extends is the keyword used to inherit or acquire the properties of a class
syntax
class superorparent{
}
class suporchild{
}
Simple inheritance
Single level
Example 1
class base
{
void display()
{
System.out.println(“parent display”);
}
}
class derived extends base
{
void display1()
{
System.out.println(“child display”);
}
}
public class simpleinherits
{
public static void main(String args[])
{
derived obj=new derived();
obj.display();
obj.display1();
}
}
Multi-Level
class base
{
void display()
{
System.out.println(“parent display”);
}
}
class inter extends base
{
void display1()
{
System.out.println(“intermediate display”);
}
}
class derived extends inter
{
void display2()
{
System.out.println(“derived display”);
}
}
public class multiinherits
{
public static void main(String args[])
{
derived obj=new derived();
obj.display();
obj.display1();
obj.display2();
}
}
When the above code is executed, it produces the following result
implement (Multiple inheritance) in java
Example 1
interface shape
{
double pi=3.14;
void calculate(float f1,float f2);
}
class circle implements shape
{
public void calculate(float x, float y)
{
System.out.println(pi*x*y);
}
}
class rectangle implements shape
{
public void calculate(float x, float y)
{
System.out.println(x*y);
}
}
class multipleinheri
{
public static void main(String args[])
{
shape s1;
circle c1=new circle();
rectangle r1=new rectangle();
s1=c1;
s1.calculate(10,1);
s1=r1;
s1.calculate(10,2);
}
}