GFG Day 10: Inheritance and Super keyword

sri parthusri parthu
9 min read

Inheritance in Java

  • Inheritance is one of the core OOP (Object-Oriented Programming) concepts. It allows one class to acquire (get) the properties (variables, methods) of another class.

  • The main advantage of inheritance is “code reusability.”

  • If we want a class to inherit, we have to use the “extend” keyword.

  • A class that gives its properties to another class is called a parent class/super class.

  • A class that gets its properties from another class is called a child class/sub class.

Syntax of Inheritance

class Parent {
    // properties and methods
}

class Child extends Parent {
    // additional properties and methods
}

Why Use Inheritance in Java

  • The main use case of inheritance in Java.

    1. Code reusability: You can define common logic once in the superclass and reuse it in multiple subclasses, so there is no need to write the method name in the subclass. It is inherited from the superclass.

    2. Method Overriding: Method overriding is achievable only through inheritance, where a child class can override parent methods to change behavior.

    3. Improve Maintainability: If you need to fix or change a common behavior, you can do it in the parent class and all child classes get the update.

Update once, reflect everywhere.

Key Terminologies Used in Java Inheritance

  1. class:

    • In inheritance, we use class as a parent (superclass) and child (subclass). It is the template or blueprint to create an object.
class Animal {
    void sound() { 
    // code.....
    }
}
  1. superclass/parent class:

    • The class whose member is a field/method is inherited and it is extended by another classes.
class Animal {
    void sound() {
        System.out.println("Animal makes sounds");
    }
}
  1. subclass/class:

    • The class that inherits from the superclass. It can use, override, or extend the parent’s functionality.
class Dog extends Animal {
    void sound() {
        System.out.println("Dog Barking");
    }
}
  1. extend keyword:

    • It is used to create a relationship between child and parent class.
class Child extends Parent { }

How Does Inheritance Work in Java?

  • Java uses the extends keyword for inheritance. It makes it possible for the subclass to inherit the superclass's fields and methods. A class that extends another class inherits all of the parent class's non-primitive members, such as fields and methods, and has the ability to override or add new functionality to them.

inheritance-660x454

Implementation:

// Parent class
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

// Child class
class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

// Child class
class Cat extends Animal {
    void sound() {
        System.out.println("Cat meows");
    }
}

// Child class
class Cow extends Animal {
    void sound() {
        System.out.println("Cow moos");
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Animal a;
        a = new Dog();
        a.sound();  // Output: Dog barks

        a = new Cat();
        a.sound();  // Output: Cat meows

        a = new Cow();
        a.sound();  // Output: Cow moos
    }
}

Output

Dog barks
Cat meows
Cow moos

Explanation:

  • Animal is the parent class.

  • Dog, Cat, and Cow are derived classes that extend the Animal class and provide specific implementations of the sound() method.

  • The Main class is the driver class that creates objects and demonstrates runtime polymorphism using method overriding.

Types of Inheritance in Java

inheritance

Below are the different types of inheritance that are supported by Java.

  • Single Inheritance

  • Multilevel Inheritance

  • Hierarchical Inheritance

  • Multiple Inheritance

  • Hybrid Inheritance

  1. Single Inheritance

  • In single inheritance, we have one parent class and one child class.

inheritence

Example

//Super class
class Vehicle {
    Vehicle() {
        System.out.println("This is a Vehicle");
    }
}

// Subclass 
class Car extends Vehicle {
    Car() {
        System.out.println("This Vehicle is Car");
    }
}

public class Test {
    public static void main(String[] args) {
        // Creating object of subclass invokes base class constructor
        Car obj = new Car();
    }
}

Output

This is a Vehicle
This Vehicle is Car
  1. Multi-level Inheritance:

  • In multi-level inheritance, there will be a minimum of three classes, and the child class will become the parent class.

Multilevel-inheritence2

Example

class Vehicle {
    Vehicle() {
        System.out.println("This is a Vehicle");
    }
}
class FourWheeler extends Vehicle {
    FourWheeler() {
        System.out.println("4 Wheeler Vehicles");
    }
}
class Car extends FourWheeler {
    Car() {
        System.out.println("This 4 Wheeler Vehicle is a Car");
    }
}
public class Geeks {
    public static void main(String[] args) {
        Car obj = new Car(); // Triggers all constructors in order
    }
}

Output

This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehicle is a Car
  1. Hierarchical Inheritance

  • In hierarchical inheritance, there will be one parent class and more than one child class.

Hierarchical-inheritance

Example

class Vehicle {
    Vehicle() {
        System.out.println("This is a Vehicle");
    }
}

class Car extends Vehicle {
    Car() {
        System.out.println("This Vehicle is Car");
    }
}

class Bus extends Vehicle {
    Bus() {
        System.out.println("This Vehicle is Bus");
    }
}

public class Test {
    public static void main(String[] args) {
        Car obj1 = new Car(); 
        Bus obj2 = new Bus(); 
    }
}

Output

This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus
  1. Hybrid Inheritance

  • In hybrid inheritance there will be the combination of two or more type of inheritance.

hybrid-inheritance

Java IS-A type of relationship

  • Now, based on the above example, in object-oriented terms, the following are true:

    • SolarSystem is the superclass of the Earth class.

    • SolarSystem is the superclass of the Mars class.

    • Earth and Mars are subclasses of the SolarSystem class.

    • Moon is a subclass of both the Earth and SolarSystem classes.

public class SolarSystem {
}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}

Now, based on the above example, in object-oriented terms, the following are true:

→ SolarSystem is the superclass of the Earth class.

→ SolarSystem is the superclass of the Mars class.

→ Earth and Mars are subclasses of the SolarSystem class.

→ Moon is a subclass of both the Earth and SolarSystem classes.

Example

class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
public class Moon extends Earth {
    public static void main(String args[])
    {
        SolarSystem s = new SolarSystem();
        Earth e = new Earth();
        Mars m = new Mars();

        System.out.println(s instanceof SolarSystem);
        System.out.println(e instanceof Earth);
        System.out.println(m instanceof SolarSystem);
    }
}

Output

true
true
true
  1. Multiple Inheritance (Through Interfaces)

  • In multiple inheritance, there will be more than one parent class and child class.

inheritence3

  • In Java, if we want to implement multiple inheritance, we have to use the "interface" and "implements" keywords.

Example

interface LandVehicle {
    default void landInfo() {
        System.out.println("This is a LandVehicle");
    }
}
interface WaterVehicle {
    default void waterInfo() {
        System.out.println("This is a WaterVehicle");
    }
}
// Subclass implementing both interfaces
class AmphibiousVehicle implements LandVehicle, WaterVehicle {
    AmphibiousVehicle() {
        System.out.println("This is an AmphibiousVehicle");
    }
}
public class Test {
    public static void main(String[] args) {
        AmphibiousVehicle obj = new AmphibiousVehicle();
        obj.waterInfo();
        obj.landInfo();
    }
}

Output

This is an AmphibiousVehicle
This is a WaterVehicle
This is a LandVehicle

Super Keyword in Java

  • In Java, the super keyword refers to the immediate parent class (superclass) of a subclass. It is used to access members (variables, methods, constructors) of the parent class from a child class.

Uses of super Keyword

PurposeDescription
→ Access parent class variableWhen child and parent have same variable names
→ Call parent class methodTo call overridden method of parent
→ Call parent class constructorTo invoke parent class constructor explicitly

Implementing the super keyword in Java

  • Super keywords are mainly used in the following contexts, which are listed below:
  1. Use of super with Variables

  • This scenario occurs when a child class and parent class have the same data members. In that case, there is a possibility of ambiguity for the JVM.

  • Real-world example: Suppose there is a child, whose name is "Max" and the child has also a parent named "Max". Normally, to refer to the parent, we would say "parent Max", this is similar to using super.maxSpeed.

Example

// Super keyword with variable 

// Base class vehicle
class Vehicle {
    int maxSpeed = 120;
}

// sub class Car extending vehicle
class Car extends Vehicle {
    int maxSpeed = 180;

    void display()
    {
        // print maxSpeed from the vehicle class 
        // using super
        System.out.println("Maximum Speed: "
                           + super.maxSpeed);
    }
}

// Driver Program
class Test {
    public static void main(String[] args)
    {
        Car small = new Car();
        small.display();
    }
}

Output

Maximum Speed: 120

Explanation: In the above example, both the base class and subclass have a member maxSpeed. We could access the maxSpeed of the base class in the subclass using the super keyword.

  1. Use of super with Methods

  • This is used when we want to call the parent class method. So, whenever a parent and child class have the same-named methods, then to resolve ambiguity, we use the super keyword.

  • Real-world Example: It is simply just like when we want to listen to our parents' advice instead of our own decision, super.methodName() helps us follow the parents' behavior in code.

Example

// superclass Person
class Person {
    void message()
    {
        System.out.println("This is person class\n");
    }
}

// Subclass Student
class Student extends Person {
    void message()
    {
        System.out.println("This is student class");
    }

    // Note that display() is
    // only in Student class
    void display()
    {
        // will invoke or call current
        // class message() method
        message();

        // will invoke or call parent
        // class message() method
        super.message();
    }
}

// Driver Program
class Test {
    public static void main(String args[])
    {
        Student s = new Student();

        // calling display() of Student
        s.display();
    }
}

Output

This is student class
This is person class

Explanation: In the above example, we have seen that if we only call method message() then, the current class message() is invoked but with the use of the super keyword, message() of the superclass could also be invoked.

  1. Use of super with Constructors

  • The super keyword can also be used to access the parent class constructor. One more important thing is that ‘super’ can call both parametric as well as non-parametric constructors depending on the situation.

  • Real-world Example: Before a child born, first the parent exists. Similarly, the parent class constructor must be called before the child's constructor finishes it's work.

Example

// superclass Person
class Person {
    Person()
    {
        System.out.println("Person class Constructor");
    }
}

// subclass Student extending the Person class
class Student extends Person {
    Student()
    {
        // invoke or call parent class constructor
        super();

        System.out.println("Student class Constructor");
    }
}

// Driver Program
class Test {
    public static void main(String[] args)
    {
        Student s = new Student();
    }
}

Output

Person class Constructor
Student class Constructor

Explanation: In the above example, we have called the superclass constructor using the keyword "super" via the subclass constructor.

Important Rules About super

  1. super() must be the first line in a constructor.

  2. If you don’t call super() explicitly, Java adds it automatically (only if the parent has a no-arg constructor).

  3. Cannot use super in static contexts.

  4. You can’t call private methods or access private variables using super.


Happy Learning

Thanks For Reading! :)

SriParthu 💝💥

0
Subscribe to my newsletter

Read articles from sri parthu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sri parthu
sri parthu

Hello! I'm Sri Parthu! 🌟 I'm aiming to be a DevOps & Cloud enthusiast 🚀 Currently, I'm studying for a BA at Dr. Ambedkar Open University 📚 I really love changing how IT works to make it better 💡 Let's connect and learn together! 🌈👋