- Getting the properties from one class object to other class is known as inheritance.
- In this inheritance will have parent class and child class so getting the properties of parent class object to child class object known as inheritance.
- Inheritance means to take something that already made.
- Inheritance can be implemented in java by using "extends" and "implements' keywords
- In this we have two types.
- Multilevel inheritance
- Multiple inheritance
Multilevel inheritance:
- Getting the properties from super class object to sub class object level wise with different priorities known as multiple inheritance.
Super class:
- package instanceofjava;
- public class Super {
- int a,b;
- void add(){
- System.out.println((a+b));
- }
- }
Sub class:
- package instanceofjava;
- public class Sub extends Super {
- void show(){
- System.out.println("this is sub class show() method");
- }
- public static void main(String [] args){
- Sub obj= new Sub();
- obj.a=1;
- obj.b=2;
- obj.add();
- obj.show();
- }
- }
Output:
- 3
- this is sub class show() method
Example program #2:
- package instanceofjava;
- public class A {
- int a,b;
- public void show(){
- System.out.println("A class show method");
- }
- }
- package instanceofjava;
- public class B extends A{
- public void print(){
- System.out.println("B class print method");
- }
- }
- package instanceofjava;
- public class C extends B{
- public void display(){
- System.out.println("C class display method");
- }
- public static void main(String [] args){
- C obj= new C();
- obj.print();
- obj.show();
- obj.display();
- }
- }
Output:
- B class print() method
- A class show method
- Class C display method
Multiple inheritance:
- Multiple inheritance means getting the properties from one class object to multiple class object with different priority.
- Multiple inheritance concept is not supported by java
- package instanceofjava;
- public class A {
- public void show(){
- System.out.println("A class show method");
- }
- }
- package instanceofjava;
- public class b {
- public void show(){
- System.out.println("B class show method");
- }
- }
- package instanceofjava;
- public class C extends A,B { // not supported by java
- public void print(){
- System.out.println("C class print method");
- }
- }
- Why java does not supports multiple inheritance check this for more information.
You Might Like:
1. Java Interview Programs On Core Java
2. Java Interview Programs On Collections
3. What is The Output Of Following Programs Java Interview:
4. Java Concept and Example Program
No comments