In this tutorial, we will write an Inheritance program in java. Before that, you should have knowledge on the following topic in Java.
Basic Example for Inheritance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Dog { void dogName() { System.out.println("My Name is Bruno"); } } class Breed extends Dog { void myBreed() { System.out.println("German Shepard"); } } public class Main { public static void main(String args[]) { Breed d = new Breed(); d.dogName(); d.myBreed(); } } |
Output:
My Name is Bruno
German Shepard
Example of Single Inheritance in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class SuperClass { public void methodSuper() { System.out.println("Super class method"); } } class SubClass extends SuperClass { public void methodBase() { System.out.println("Sub class method"); } } public class Main { public static void main(String args[]) { SubClass s = new SubClass(); s.methodSuper(); s.methodBase(); } } |
Output:
Super class method
Base class method
Example of Multilevel Inheritance in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class FirstClass { public void displayFirst() { System.out.println("I am First Class"); } } class SecondClass extends FirstClass { public void displaySecond() { System.out.println("I am Second Class"); } } class ThirdClass extends SecondClass { public void displayThird() { System.out.println("I am Third Class"); } } public class Main { public static void main(String[] args) { ThirdClass three = new ThirdClass(); three.displayFirst(); three.displaySecond(); three.displayThird(); } } |
Output:
I am First Class
I am Second Class
I am Third Class
Example of Hierarchical Inheritance in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | class Animal { void Dog() { System.out.println("I am dog");} } class Cat extends Animal { void sleep() { System.out.println("I am Cat and I sleep"); } } class Horse extends Animal { void run() { System.out.println("I am Horse and I run"); } } public class Main { public static void main(String args[]) { Horse h=new Horse(); h.Dog(); h.run(); Cat c=new Cat(); c.Dog(); c.sleep(); } } |
Output:
I am dog
I am Horse and I run
I am dog
I am Cat and I sleep