OOP_3|Inheritance in Java

Nikita pandey
7 min readFeb 21, 2023

Inheritance helps to reduce code duplication and increase code reusability, as the derived class can inherit and reuse the properties and behaviors of the base class. This allows developers to write less code and organize their code more effectively.

Inheritance in Java

Inheritance is one of the key features of object-oriented programming. It allows the creation of a new class, known as the subclass, which is based on an existing class, known as the superclass. The subclass inherits all the attributes and methods of the superclass, and can also add new attributes and methods of its own.

How to inherit a class in Java?

To inherit a class in Java, you simply incorporate the definition of one class into another by using the extends keyword.

class Subclass extends Superclass {
// body of class
}

Java supports the following types of inheritance:

  1. Single Inheritance: In Single inheritance, a subclass can inherit the properties and methods of only one superclass. Java doesn’t allow multiple inheritances of classes, which means that a class cannot inherit from more than one class at the same time. For example:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

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

In this example, class Dog is inheriting the properties and methods of class Animal. Dog can access the eat() method of class Animal.

2. Multilevel Inheritance: In Multilevel inheritance, a subclass can inherit the properties and methods of a superclass, and then act as a superclass for another subclass. This means that a subclass can also act as a superclass, and can inherit properties and methods from its parent class. For example:

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

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

class Poodle extends Dog {
void play() {
System.out.println("Poodle is playing");
}
}

3. Hierarchical Inheritance

Hierarchical inheritance is when multiple child classes inherit from a single parent class.

// Parent Class
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}

// Child Class 1
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}

// Child Class 2
class Cat extends Animal {
public void meow() {
System.out.println("Cat is meowing");
}
}

In the example above, the classes Dog and Cat are both inheriting from the class Animal. They each have access to all the public and protected methods of Animal, including the eat() method. Dog has its own method bark(), and Cat has its own method meow().

4. Multiple Inheritance

Java does not support multiple inheritance, which is when a class inherits from multiple parent classes. However, Java does support a form of multiple inheritance through interfaces.

interface Animal {
public void eat();
}

interface Mammal {
public void giveBirth();
}

class Dog implements Animal, Mammal {
public void eat() {
System.out.println("Dog is eating");
}

public void giveBirth() {
System.out.println("Dog is giving birth");
}
}

In the example above, the class Dog is implementing both the Animal and Mammal interfaces, which each have their own methods. Dog must implement all the methods of the interfaces it implements, which in this case are eat() from Animal and giveBirth() from Mammal.

5.. Hybrid inheritance

It is a combination of multiple and hierarchical inheritance. In this type of inheritance, a class is derived from two or more base classes, and at least one of the base classes is derived from another base class.

// Base class
class Vehicle {
void display() {
System.out.println("I am a vehicle");
}
}

// First derived class
class Car extends Vehicle {
void display() {
System.out.println("I am a car");
}
}

// Second derived class
class Truck extends Vehicle {
void display() {
System.out.println("I am a truck");
}
}

// Derived class from both Car and Truck
class SUV extends Car, Truck {
void display() {
System.out.println("I am an SUV");
}
}

In this example, the Vehicle class is the base class, and the Car and Truck classes are derived from it. The SUV class is then derived from both Car and Truck.

However, Java does not support multiple inheritance, so the code above would result in a compile-time error. To implement hybrid inheritance in Java, you would need to use interfaces and/or abstract classes to achieve the desired functionality.

Photo by Riku Lu on Unsplash

Access Modifiers in Inheritance

In a subclass, you can access all public and protected members of the superclass. However, you cannot access any private members of the superclass. This is because private members are not visible to the subclass.

Superclass Variable Referencing a Subclass Object

In Java, a superclass variable can reference a subclass object. This is known as upcasting, where an object of a subclass is treated as an object of its superclass. Here’s an example to demonstrate this concept:

public class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}

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

public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
animal.makeSound(); // Calls Dog's makeSound method
}
}

In this example, the Animal class is the superclass, and the Dog class is the subclass. The Dog class inherits the makeSound method from its superclass, but it overrides the method to make a specific sound.

In the Main class, we create a new Dog object and assign it to an Animal variable using upcasting. The animal variable can only access the Animal class's methods and properties. However, since Dog is a subclass of Animal, it can override the makeSound method, and the Dog class's version of the method is called when we invoke animal.makeSound().

This is a useful technique when you want to write a method that can work with objects of multiple related classes. By accepting a superclass object as a parameter, your method can accept objects of any subclass of that superclass. This is known as polymorphism, and it’s one of the key features of object-oriented programming.

Using the Super Keyword

The “super” keyword is used to refer to the immediate superclass of a class. It can be used in two ways:

  1. Using “super” to Call the Superclass Constructor

In Java, when you create a subclass, the first line of its constructor should always call the constructor of its superclass using the “super” keyword. This is necessary because the subclass inherits all the fields and methods of its superclass, and the superclass constructor is responsible for initializing those fields.

public class Vehicle {
int wheels;

public Vehicle(int wheels) {
this.wheels = wheels;
}
}

public class Car extends Vehicle {
int doors;

public Car(int wheels, int doors) {
super(wheels); // call the superclass constructor
this.doors = doors;
}
}
super.printMessage();
}

In this example, the “Car” class extends the “Vehicle” class. The “Car” constructor takes two parameters, “wheels” and “doors”, and passes the “wheels” parameter to the “Vehicle” constructor using the “super” keyword. This ensures that the “wheels” field of the “Vehicle” class is initialized properly.

2. Using “super” to Access a Hidden Member of the Superclass.

When a subclass defines a member with the same name as a member in the superclass, the subclass member “hides” the superclass member. However, you can still access the superclass member using the “super” keyword.

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

public class Cat extends Animal {
public void makeSound() {
System.out.println("The cat meows");
}

public void makeAnimalSound() {
super.makeSound(); // call the superclass method
}
}

In this example, the “Cat” class extends the “Animal” class and overrides the “makeSound” method. However, the “makeAnimalSound” method uses the “super” keyword to call the “makeSound” method of the superclass, which outputs “The animal makes a sound”.

Using the final Keyword

In Java, the final keyword is used to restrict the inheritance of a class or the override of a method. When a class is declared as final, it cannot be extended or subclassed by any other class. Similarly, when a method is declared as final, it cannot be overridden by any subclass. Here is how to use the final keyword in inheritance in Java:

  1. Declaring a Final Class

To declare a class as final, simply use the final keyword before the class keyword. Here is an example:

final public class MyFinalClass {
// class body
}

In this example, the MyFinalClass is declared as final, which means that it cannot be extended by any other class.

2. Extending a Final Class

When a class is declared as final, it cannot be extended by any other class. If you try to extend a final class, you will get a compilation error. Here is an example:

public class MyExtendedClass extends MyFinalClass {
// class body
}

In this example, the MyExtendedClass is trying to extend the MyFinalClass, which is a final class. Therefore, the compilation will fail with an error.

3. Declaring a Final Method

To declare a method as final, simply use the final keyword before the method name. Here is an example:

public class MyBaseClass {
final public void myFinalMethod() {
// method body
}
}

4. Overriding a Final Method

When a method is declared as final, it cannot be overridden by any subclass. If you try to override a final method, you will get a compilation error. Here is an example:

public class MyDerivedClass extends MyBaseClass {
public void myFinalMethod() {
// method body
}
}

In this example, the MyDerivedClass is trying to override the myFinalMethod of its parent class, which is declared as final. Therefore, the compilation will fail with an error.

In conclusion, the final keyword is used to restrict the inheritance of a class or the override of a method in Java. By declaring a class or a method as final, you can prevent other classes from extending it or overriding it, respectively.

Thank you:)

--

--

Nikita pandey

Python developer| Data science student| detective by nature| into art,AI, and books