top of page

Java Inheritance: Understanding Inheritance in Java Programming with Examples

shubhangisingh453


In Java, inheritance is a powerful mechanism that allows a class to inherit properties and behavior from another class. In this way, we can reuse existing code and create new classes that are similar to existing ones, but with additional features or modifications. In this answer, we will cover each and every topic related to inheritance in Java, along with examples.


📘 What is Inheritance in Java?


Inheritance is a feature in Java that allows one class to inherit properties and behavior from another class. The class that is being inherited from is called the superclass or parent class, while the class that inherits from it is called the subclass or child class. The subclass can access all of the public and protected members of the superclass, and it can also define its own members.

Here's an example:


class Animal {
  public void eat() {
    System.out.println("The animal is eating");
  }
}

class Dog extends Animal {
  public void bark() {
    System.out.println("The dog is barking");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog myDog = new Dog();
    myDog.eat();  // Output: The animal is eating
    myDog.bark(); // Output: The dog is barking
  }
}

In this example, we have two classes: Animal and Dog. The Dog class extends the Animal class, which means that it inherits the eat() method from the Animal class. The Dog class also defines its own method, bark(). In the main() method, we create an object of the Dog class and call both the eat() and bark() methods on it.


📘 Types of Inheritance in Java


There are five types of inheritance in Java:

  • Single inheritance: A subclass can only inherit from a single superclass.

  • Multilevel inheritance: A subclass can inherit from a superclass, which in turn can inherit from another superclass, and so on.

  • Hierarchical inheritance: Multiple subclasses can inherit from a single superclass.

  • Multiple inheritance (not supported in Java): A subclass can inherit from multiple superclasses.

  • Hybrid inheritance (not supported in Java): A combination of multiple and multilevel inheritance.

Here's an example of multilevel inheritance:


class Animal {
  public void eat() {
    System.out.println("The animal is eating");
  }
}

class Mammal extends Animal {
  public void walk() {
    System.out.println("The mammal is walking");
  }
}

class Dog extends Mammal {
  public void bark() {
    System.out.println("The dog is barking");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog myDog = new Dog();
    myDog.eat();  // Output: The animal is eating
    myDog.walk(); // Output: The mammal is walking
    myDog.bark(); // Output: The dog is barking
  }
}

In this example, we have three classes: Animal, Mammal, and Dog. The Animal class has a method eat(), which is inherited by the Mammal class. The Mammal class has a method walk(), which is inherited by the Dog class. The Dog class defines its own method bark(). In the main() method, we create an object of the Dog class and call all three methods on it.


📘 is - a Relationship in inheritance


In Java, the is-a relationship is a key concept in inheritance, and it refers to the relationship between a subclass and its superclass. The is-a relationship means that an object of a subclass is also an object of its superclass, and can be treated as such.

For example, consider the following class hierarchy:


class Animal {
  public void eat() {
    System.out.println("The animal is eating");
  }
}

class Dog extends Animal {
  public void bark() {
    System.out.println("The dog is barking");
  }
}

In this example, we have a Dog class that extends the Animal class. This means that a Dog object is also an Animal object, and can be treated as such. For instance, we can create a Dog object and assign it to an Animal variable:


Animal myAnimal = new Dog();

We can then call the eat() method on myAnimal, even though it is a Dog object:


myAnimal.eat();
 // Output: The animal is eating

This is possible because a Dog is an Animal due to the is-a relationship between the two classes.

The is-a relationship is an important concept in object-oriented programming because it allows us to create classes that build upon existing classes and inherit their properties and behavior. By doing so, we can reuse existing code and create new classes that are more specialized and tailored to our needs.


📘 Method Overriding in Inheritance


Method overriding is a feature of Java inheritance that allows a subclass to provide its own implementation of a method that is already defined in its superclass. When a subclass defines a method with the same name, return type, and parameters as a method in its superclass, it is said to be overriding the superclass method.

Here is an example of method overriding:


class Animal {
  public void makeSound() {
    System.out.println("The animal makes a sound");
  }
}

class Dog extends Animal {
  @Override
public void makeSound() {
    System.out.println("The dog barks");
  }
}

In this example, the Dog class extends the Animal class and overrides the makeSound() method of the Animal class. The @Override annotation is used to indicate that the makeSound() method is intended to override the superclass method.

Now, when we create a Dog object and call its makeSound() method, it will output "The dog barks" instead of "The animal makes a sound":


Dog myDog = new Dog();
myDog.makeSound();
 // Output: The dog barks

Note that method overriding allows us to provide a more specialized implementation of a method in the subclass. In this example, the Dog class knows how to bark, but the Animal class does not. By overriding the makeSound() method in the Dog class, we can make sure that any Dog object will bark when its makeSound() method is called.

Method overriding is a powerful feature of Java inheritance, but it is important to use it carefully. When we override a method in a subclass, we are changing the behavior of the superclass, and this can have unintended consequences if we are not careful. We should only override methods when we know exactly what we are doing and why we are doing it.


📘 Super Keyword in Inheritance


In Java inheritance, the super keyword is used to refer to the superclass of a subclass. We can use super to call the constructor, methods, and variables of the superclass.

Here are some examples of how to use super in Java inheritance:


âš¡ Calling the constructor of the superclass


When we create an object of a subclass, the constructor of the superclass is called implicitly. We can also explicitly call the constructor of the superclass using the super() constructor call. Here is an example:


class Animal {
  private String name;
  
  public Animal(String name) {
    this.name = name;
  }
}

class Dog extends Animal {
  public Dog(String name) {
    super(name);
  }
}

In this example, the Animal class has a constructor that takes a name parameter. The Dog class extends the Animal class and has its own constructor that takes a name parameter. Inside the constructor of Dog, we call the constructor of the superclass using the super(name) constructor call.


âš¡ Calling a method of the superclass


We can use super to call a method of the superclass from within a method of the subclass. Here is an example:


class Animal {
  public void makeSound() {
    System.out.println("The animal makes a sound");
  }
}

class Dog extends Animal {
  @Override
public void makeSound() {
    super.makeSound();
    System.out.println("The dog barks");
  }
}

In this example, the Dog class overrides the makeSound() method of the Animal class. Inside the makeSound() method of Dog, we call the makeSound() method of the superclass using super.makeSound(). This allows us to reuse the implementation of the makeSound() method in the Animal class, while also adding our own specialized behavior for the Dog class.


âš¡ Accessing a variable of the superclass


We can use super to access a variable of the superclass from within a method of the subclass. Here is an example:


class Animal {
  protected String name;
  
  public Animal(String name) {
    this.name = name;
  }
}

class Dog extends Animal {
  public Dog(String name) {
    super(name);
  }
  
  public void printName() {
    System.out.println("The dog's name is " + super.name);
  }
}

In this example, the Animal class has a name variable that is set in its constructor. The Dog class extends the Animal class and has its own printName() method that accesses the name variable of the superclass using super.name. This allows us to access the name variable of the superclass from within the Dog class.


📘 Inheritance Protected Members


In Java inheritance, the protected access modifier is used to specify that a member (variable or method) is accessible within the same package and within its subclasses, even if the subclasses are in a different package.

Here is an example of using protected members in inheritance:


package myPackage;

public class Animal {
  protected String name;
  
  protected void sleep() {
    System.out.println("The animal is sleeping");
  }
}

package myPackage;

public class Dog extends Animal {
  public Dog(String name) {
    this.name = name;
  }
  
  public void bark() {
    System.out.println(name + " is barking");
  }
  
  public void sleep() {
    System.out.println(name + " is sleeping");
    super.sleep();
  }
}

package myOtherPackage;

import myPackage.Dog;

public class Main {
  public static void main(String[] args) {
    Dog myDog = new Dog("Buddy");
    myDog.bark(); // Output: Buddy is barking
    myDog.sleep(); // Output: Buddy is sleeping \n The animal is sleeping
  }
}

In this example, the Animal class has a name variable and a sleep() method that are both marked as protected. The Dog class extends the Animal class and overrides the sleep() method. Inside the sleep() method of Dog, we call the sleep() method of the superclass using super.sleep().

In the Main class, we create a Dog object and call its bark() and sleep() methods. Both methods are able to access the name variable and the sleep() method of the superclass because they are marked as protected.

Using protected members in inheritance allows us to create more specialized subclasses that can access and modify the behavior of the superclass. However, it is important to use protected members carefully and only when necessary, as they can also introduce complexity and make the code harder to understand and maintain.


♦ Advantage of using Inheritance


Inheritance is one of the fundamental concepts of object-oriented programming (OOP) and has several advantages:

  1. Code reusability: Inheritance enables us to create new classes based on existing classes, thereby inheriting all the properties and behaviors of the parent class. This can save time and effort as we can reuse existing code instead of writing it from scratch.

  2. Maintainability: Inheritance allows us to create a hierarchical structure of classes, with each class inheriting the properties and behaviors of its parent class. This makes it easier to modify and maintain the code as changes made to the parent class are automatically propagated to all the subclasses.

  3. Polymorphism: Inheritance is a key component of polymorphism, which allows us to create objects of different classes that can be treated as objects of a common superclass. This enables us to write more flexible and extensible code as we can use the same code to operate on objects of different classes.

  4. Encapsulation: Inheritance can be used in conjunction with access modifiers to achieve encapsulation, which is the process of hiding the internal details of a class and exposing only the necessary information to the outside world. By making the properties and methods of the parent class private or protected, we can ensure that they are not accessible from outside the class and can only be accessed by the subclasses.

  5. Abstraction: Inheritance is also a key component of abstraction, which is the process of hiding the implementation details of a class and exposing only the interface. By using inheritance to create abstract classes or interfaces, we can define a set of common methods and properties that are shared by a group of classes, without specifying their implementation details.

Overall, inheritance is a powerful tool that enables us to create more efficient, maintainable, and extensible code. However, it should be used carefully and only when appropriate, as overuse of inheritance can lead to complex and hard-to-maintain code.


Thanks for reading, and happy coding!


Java Inheritance: Understanding Inheritance in Java Programming with Examples - > Understanding Method Overriding and the use of super Keyword in Java




Recent Posts

See All
bottom of page