DEV Community

Saravanan B
Saravanan B

Posted on

Core Java - Inheritance

Single Inheritance
Implicitly every class inherits the java.lang.object class.

Image description

Multilevel Inheritance
In this we have a parent class and child class extending parent class.

while creating object for child class using that object we can call the parent class methods.

Image description

If we create a object for child class and object address is same for parent class and child class.

Hierarchical inheritance
A vehicle class has a fuel method a bus and car class extend vehicle class.

Method Overriding
The fuel method return diesal for bus and petrol for car this is method overriding. Still the method name and signature is same.

Class Vehicle{
public String fuel(){
return "null";
}
}
Enter fullscreen mode Exit fullscreen mode
Class bike extends Vehicle{
@override 
public String fuel(){
return "petrol";
}
}
Enter fullscreen mode Exit fullscreen mode
class bus extends Vehicle{
@override 
public String fuel(){
return "diesal";
}
}
Enter fullscreen mode Exit fullscreen mode
class Main{
public static void main(String[] args){
 Bike b = new Bike();
 System.out.println(b.fuel());
 Bus b1 = new Bus();
 System.out.println(b1.fuel());
}
}
Enter fullscreen mode Exit fullscreen mode

Super keyword
Super keyword is used to point out parent class.

public class Parent {
    void f1() {
        System.out.println("inside parent f1");
    }
}

Enter fullscreen mode Exit fullscreen mode
public class Child extends Parent{
    void f1() {
        super.f1();
        System.out.println("inside child f1");
    }
}
Enter fullscreen mode Exit fullscreen mode
public class Test {
    public static void main(String[] args) {
        Child c = new Child();
        c.f1();
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Constructor Chaining
Is a feature we can access parent and child constructor in single object creation.

public class SuperClass {
    int x;

    public SuperClass() {
        System.out.println("No args constructor");
    }

    public SuperClass(int x) {
        this();
        this.x = x;
        System.out.println("All args Constructor");
    }

}
Enter fullscreen mode Exit fullscreen mode
public class ChildClass extends SuperClass{
    ChildClass(){
        this(10);
        System.out.println("No args child class constrctor");
    }
    ChildClass(int x){
        super(x);
        System.out.println("No args child class constrctor");
    }
    public static void main(String[] args) {
        ChildClass c = new ChildClass();

    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)