13.1 Inheritance and Polymorphism in Java: Concept of Inheritance

Inheritance is one of the fundamental pillars of object-oriented programming (OOP), and Java, being a language that adopts this paradigm, offers robust resources for its implementation. Inheritance is a mechanism that allows a new class to derive properties and behaviors from an existing class. The class that is inherited is called a base class, superclass, or parent class, while the class that inherits is known as a derived class, subclass, or child class.

In practice, inheritance makes it possible to reuse code and create a hierarchy of related classes. This not only saves time and effort in software development, but also helps keep the code organized, easier to maintain and expand.

How Inheritance Works in Java

In Java, inheritance is performed with the extends keyword. When a class is defined as the extension of another, it inherits all non-private fields (attributes) and methods of the parent class. This means that the child class can use these members as its own.

Example:

class Vehicle {
    protected String brand = "Ford"; // Vehicle class attribute
    public void honk() { // Vehicle class method
        System.out.println("Tuut, tuut!");
    }
}

class Car extends Vehicle {
    private String modelName = "Mustang"; // Car class attribute
    public static void main(String[] args) {
        // Create an object of the Car class
        Car myCar = new Car();

        // Call the Vehicle class method
        myCar.honk();

        // Accesses the Vehicle class attribute
        System.out.println(myCar.brand + " " + myCar.modelName);
    }
}

In this example, Car is a subclass of Vehicle. The Car class inherits the honk method and the brand attribute from the Vehicle class, and also defines its own attribute, modelName.

Method Overriding

A subclass in Java can override the methods of the superclass. This is done when the subclass needs a specific implementation for an inherited method. Superscripting is a form of polymorphism, which will be discussed later.

Example:

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

class Pig extends Animal {
    public void sound() {
        System.out.println("The pig says: wee wee");
    }
}

class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal(); // Create an object of the Animal class
        Animal myPig = new Pig(); // Create an object of the Pig class

        myAnimal.sound();
        myPig.sound();
    }
}

In this example, the Pig class overrides the sound method of the Animal class. When the method is called on the myPig object, the implementation of the Pig class is used, not that of the Animal class.

Using super

The super keyword in Java is used within subclass methods to refer to members (methods or attributes) of the superclass. This is especially useful when we are overriding methods but still want to access the superclass's implementation.

Example:

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

class Pig extends Animal {
    public void sound() {
        super.sound(); // Call the superclass method
        System.out.println("The pig says: wee wee");
    }
}

Here, the Pig class calls the sound method of the Animal superclass before executing its own code.

Polymorphism in Java

Polymorphism, another pillar of OOP, allows objects from different classes to be treated as objects from a common superclass. This is particularly powerful in combination with inheritance, as it allows a single method or class to operate on objects of different classes.

Polymorphism in Java is, for the most part, accomplished through method overloading and overriding. Overloading occurs when two or more methods in the same class have the same name but different parameters. Overriding, as we have seen, is when a subclass provides a specific implementation for a method that is already provided by its superclass.

Example of polymorphism:

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

class Pig extends Animal {
    public void sound() {
        System.out.println("The pig says: wee wee");
    }
}

class Dog extends Animal {
    public void sound() {
        System.out.println("The dog says: bow wow");
    }
}class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        Animal myPig = new Pig();
        Animal myDog = new Dog();

        myAnimal.sound();
        myPig.sound();
        myDog.sound();
    }
}

In this example, the Main class creates objects of different types, but they are all treated as instances of the Animal class. This demonstrates polymorphism, as the sound method behaves differently depending on the type of object that invokes it.

Conclusion

Inheritance and polymorphism are key concepts in object-oriented programming and are extensively used in Java to create reusable code and extensible systems. By understanding and applying these concepts, developers can write cleaner, more modular, and easier to maintain code.

This Java course is expected to provide you with a solid understanding of these concepts, allowing you to apply them in real-world scenarios and build robust, efficient applications.

Now answer the exercise about the content:

Which of the following statements about inheritance in Java is correct?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Inheritance and Polymorphism in Java: 'extends' Keyword

Next page of the Free Ebook:

86Inheritance and Polymorphism in Java: 'extends' Keyword

5 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text