Core Java SQL Oracle PHP Examples JSP JDBC MORE

Java Inheritance


Inheritance is the process of deriving child class from a parent class.

parent class is known as superclass.

Child class is known as subclass

Advantage of inheritance

  1. Code reusability
  2. Code sharing

Syntax:

class Subclass-name extends Superclass-name
{
//methods and fields
}

Example

class Student{
float fees=30000;
}
class Programmer extends Student{
int fine=20000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer fees is:"+p.fees);
System.out.println("fine of Programmer is:"+p.fine);
}
}

Output :
Programmer fine is:30000
fine of programmer is:20000

Types of inheritance in java

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance

Single Inheritance in Java

Single inheritance is the process of deriving child class from base class

Example of Single Inheritance

class Fruit{
void eat(){System.out.println("eating...");}
}
class Apple extends Fruit{
void drink(){System.out.println("drinking...");}
}
class TestInheritance{
public static void main(String args[]){
Apple p=new Apple();
p.eat();
p.drink();
}
}

Output :
eating...
drinking...

Multilevel Inheritance

Multilevel inheritance is the process of deriving childclass from base class then base class from superclass

Example of Multilevel Inheritance

class Fruit{
void eat(){System.out.println("eating...");}
}
class Apple extends Fruit{
void drink(){System.out.println("drinking...");}
}
class small Apple extends Apple{
void sample(){System.out.println("sampling...");}
}
class TestInheritance2{
public static void main(String args[]){
Small Apple c=new Small Apple();
c.eat();
c.bark();
c.sample(); }}

Output :
sampling...
drinking...
eating...

Hierarchical Inheritance

Hierarchical Inheritance is the process of deriving somany class from one classes

Example of Multilevel Inheritance

class Farmer{
void cultivation(){System.out.println("cultivating...");}
}
class Rice extends Farmer{
void eat(){System.out.println("eating...");}
}
class flower extends Farmer{
void sell(){System.out.println("selling...");}
}
class TestInheritance3{
public static void main(String args[]){
Flower d=new Flower();
d.eat();
d.sell();
}
}

Output :
eating...
selling...