15. Can you explain the concept of inheritance in Java with an example?

Basic

15. Can you explain the concept of inheritance in Java with an example?

Overview

Inheritance in Java is a fundamental concept in object-oriented programming that allows one class to inherit fields and methods from another, facilitating code reuse and polymorphism. It's crucial for designing efficient and scalable software systems.

Key Concepts

  1. Superclass and Subclass: The class from which members are inherited is called the superclass, and the class that inherits those members is called the subclass.
  2. Method Overriding: Subclasses can override methods from the superclass, allowing for polymorphic behavior.
  3. Access Modifiers: They determine which classes can access the inherited members. The most common are public, protected, and private.

Common Interview Questions

Basic Level

  1. What is inheritance in Java and why is it used?
  2. How do you use the extends keyword in Java?

Intermediate Level

  1. Can a subclass override a superclass method in Java?

Advanced Level

  1. How does Java handle multiple inheritance?

Detailed Answers

1. What is inheritance in Java and why is it used?

Answer: Inheritance in Java is a mechanism where a new class, known as a subclass, is created based on an existing class, known as a superclass. It enables the subclass to inherit fields and methods of the superclass, promoting code reuse, reducing redundancy, and improving maintainability. It's used to create a hierarchical classification of classes that models the real-world relationships among entities.

Key Points:
- Facilitates code reuse.
- Enables polymorphism.
- Helps in creating a hierarchical organization of classes.

Example:

// Define a superclass
class Vehicle {
    void run() {
        System.out.println("Vehicle is running");
    }
}

// Define a subclass that inherits from Vehicle
class Car extends Vehicle {
    // Car class can inherit methods from Vehicle
}

class TestInheritance {
    public static void main(String args[]) {
        Car myCar = new Car();
        myCar.run(); // Outputs: Vehicle is running
    }
}

2. How do you use the extends keyword in Java?

Answer: In Java, the extends keyword is used in a class declaration to specify that the class is being derived from another class, known as the superclass. The derived class, called the subclass, inherits all accessible members (fields, methods) from the superclass.

Key Points:
- Basic syntax for establishing an inheritance relationship.
- The subclass gains access to the superclass's methods and fields.
- Constructors are not inherited.

Example:

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

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

class TestInheritance {
    public static void main(String args[]) {
        Dog myDog = new Dog();
        myDog.eat(); // Outputs: Animal is eating
        myDog.bark(); // Outputs: Dog barks
    }
}

3. Can a subclass override a superclass method in Java?

Answer: Yes, a subclass in Java can override methods of its superclass. This mechanism allows a subclass to provide a specific implementation of a method that is already provided by its superclass. Method overriding is a cornerstone of polymorphism in Java.

Key Points:
- Overriding requires the method in the subclass to have the same name, return type, and parameters as in the superclass.
- The @Override annotation, while not required, is recommended to indicate an overriding method.
- Dynamic method dispatch is used at runtime to resolve overridden methods.

Example:

class Animal {
    void speak() {
        System.out.println("Animal speaks");
    }
}

class Cat extends Animal {
    @Override
    void speak() {
        System.out.println("Meow");
    }
}

class TestOverride {
    public static void main(String args[]) {
        Animal myAnimal = new Cat(); // Upcasting
        myAnimal.speak(); // Outputs: Meow
    }
}

4. How does Java handle multiple inheritance?

Answer: Java does not support multiple inheritance directly through classes to avoid complexity and ambiguity issues (such as the Diamond Problem). However, Java provides a workaround through interfaces. A class in Java can implement multiple interfaces, allowing it to inherit abstract methods from multiple sources.

Key Points:
- Java uses interfaces to achieve multiple inheritance.
- A class can implement any number of interfaces.
- Interfaces can only contain abstract methods (until Java 8 introduced default and static methods).

Example:

interface WaterAnimal {
    void swim();
}

interface LandAnimal {
    void walk();
}

// Implementing multiple inheritance via interfaces
class Frog implements WaterAnimal, LandAnimal {
    public void swim() {
        System.out.println("Frog swims");
    }

    public void walk() {
        System.out.println("Frog walks");
    }
}

class TestInterfaces {
    public static void main(String args[]) {
        Frog frog = new Frog();
        frog.swim(); // Outputs: Frog swims
        frog.walk(); // Outputs: Frog walks
    }
}