Java Question Bank with Answers

 

Answers for Core Java Question Bank –

Chapter 3: Inheritance and Interfaces

Easy Level Questions (5 Marks Each)

1. What is inheritance in Java? List one key advantage of using inheritance.

Answer:
Inheritance in Java is an Object-Oriented Programming mechanism that allows a new class (subclass or derived class) to inherit properties (fields) and behaviors (methods) from an existing class (superclass or base class). It establishes an "is-a" relationship between the subclass and the superclass, meaning a subclass is a specialized version of its superclass.

Key Advantage (any one):

1.     Code Reusability: The most significant advantage is code reusability. Common methods and fields can be defined once in the superclass and then reused by all its subclasses, eliminating redundant code.

2.     Polymorphism: It supports runtime polymorphism, allowing a superclass reference variable to refer to a subclass object, enabling dynamic method dispatch.

3.     Maintainability: By structuring code hierarchically, changes to common functionalities can be made in the superclass, benefiting all subclasses, thus improving maintainability.

2. Differentiate between a superclass and a subclass in the context of Java inheritance.

Answer:

Feature

Superclass (Base Class/Parent Class)

Subclass (Derived Class/Child Class)

Definition

The class from which properties and behaviors are inherited. It serves as the blueprint for common attributes and methods shared by its descendants.

The class that inherits properties and behaviors from a superclass. It is a specialized version of the superclass and can add its own unique features or modify inherited ones

Relationship

The more general class in an "is-a" relationship.

The more specific class in an "is-a" relationship (e.g., Car is a Vehicle) (

Keywords

No specific keyword for definition, but can be extended by other classes.

Uses the extends keyword to indicate inheritance from a superclass (e.g., class Car extends Vehicle).

Access

Can provide access to its public and protected members to subclasses.

Has access to public and protected members of its superclass, and default members if they are in the same package

Example

Vehicle class (general concept)

Car, Bike, Truck classes (specific types of Vehicle)

3. What is the purpose of the super keyword in Java? Give a simple scenario where it is used.

Answer:
The
super keyword in Java is a reference variable that refers to the immediate parent class (superclass) object . It is used to access members (fields and methods) of the superclass that are hidden or overridden by the subclass, or to invoke the superclass’s constructor .

Purpose:

1.     To invoke superclass constructor: super() is used as the first statement in a subclass constructor to call a constructor of its superclass .

2.     To access superclass members: super.variableName or super.methodName() is used to access a superclass’s field or method when it has been shadowed or overridden by a member in the subclass .

Simple Scenario:
Consider a
Dog class extending an Animal class. The Animal class constructor might initialize the species and age. The Dog class constructor would call the Animal constructor using super() to handle this common initialization, then add its own specific initialization (e.g., breed).

class Animal {
    String species;
    int age;
 
    Animal {
        this.species = species;
        this.age = age;
        System.out.println("Animal constructor called.");
    }
}
 
class Dog extends Animal {
    String breed;
 
    Dog {
        super(species, age); // Calls the Animal class constructor
        this.breed = breed;
        System.out.println("Dog constructor called.");
    }
}

4. Define method overriding. What is a prerequisite for a method to be overridden?

Answer:
Method Overriding is a feature in Java where a subclass provides its own specific implementation for a method that is already defined in its superclass . When a method in a subclass has the same signature (same name, same parameters, and same return type) as a method in its superclass, it is said to override the superclass method . This allows objects of subclasses to exhibit specialized behavior while maintaining a common interface defined by the superclass.

Prerequisites for a method to be overridden:

1.     Inheritance: Method overriding can only occur in the context of inheritance; the subclass must extend the superclass .

2.     Same Signature: The method in the subclass must have the exact same name, number and type of parameters, and return type as the method in the superclass .

3.     Access Modifier: The access modifier of the overriding method (in the subclass) cannot be more restrictive than the overridden method (in the superclass) . For example, a public method in the superclass cannot be overridden as private or protected in the subclass.

4.     Non-final and Non-static: The method in the superclass must not be declared as final (because final methods cannot be overridden)  or static (because static methods are hidden, not overridden) .

5.     Non-private: The method in the superclass must not be private, as private methods are not inherited .

5. What is an abstract class in Java? Can an abstract class be instantiated directly?

Answer:
An abstract class in Java is a class that is declared with the
abstract keyword . It cannot be instantiated directly and serves as a blueprint for other classes. Abstract classes can have both abstract methods (methods declared without an implementation) and concrete methods (methods with full implementations) . They can also contain fields, constructors, and nested types.

Can an abstract class be instantiated directly?
No, an abstract class cannot be instantiated directly using the
new keyword . Since it may contain abstract methods (methods without an implementation), creating an object of an abstract class directly would result in an incomplete object that cannot fulfill all its defined behaviors. To use an abstract class, it must be extended by a concrete (non-abstract) subclass, which then provides implementations for all the inherited abstract methods . Only objects of these concrete subclasses can be created.

6. What is an interface in Java? Can an interface contain concrete method implementations?

Answer:
An interface in Java is a blueprint of a class that can contain abstract methods (methods without an implementation) and static final fields (constants) . It specifies a contract that implementing classes must adhere to, guaranteeing that they will provide implementations for all the methods declared in the interface. Interfaces achieve polymorphism and define a common type without specifying how the methods are implemented.

Can an interface contain concrete method implementations?
Historically, Java interfaces could only contain abstract methods (until Java 8). However, starting with Java 8, interfaces can contain:

1.     Default methods: These are methods with an implementation, prefixed with the default keyword . They allow adding new functionalities to an interface without breaking existing implementing classes.

2.     Static methods: These are methods with an implementation, prefixed with the static keyword . They are utility methods associated with the interface itself and cannot be overridden by implementing classes.

So, yes, an interface can now contain concrete method implementations through default and static methods.

7. Explain the use of the final keyword when applied to a method.

Answer:
When the
final keyword is applied to a method in Java, it signifies that the method cannot be overridden by any subclass .

Use:

1.     Preventing Undesired Overriding: It ensures that the specific implementation of that method, as provided in the superclass, is maintained throughout the inheritance hierarchy. This is crucial for methods that implement core logic, security-sensitive operations, or algorithms that should not be altered by subclasses .

2.     Security and Consistency: By making a method final, you can guarantee that its behavior remains consistent and that subclasses cannot introduce vulnerabilities or unexpected behavior by changing its implementation.

3.     Optimization (Historical/Minor): In older JVMs, final methods could sometimes be inlined by the compiler for minor performance gains because their implementation was guaranteed not to change. Modern JVMs perform sophisticated optimizations regardless, so this is rarely a primary reason today.

Example:

class Vehicle {
    // Final method: cannot be overridden by subclasses
    final void drive() {
        System.out.println("Vehicle is driving.");
    }
 
    // Normal method: can be overridden
    void start() {
        System.out.println("Vehicle started.");
    }
}
 
class Car extends Vehicle {
    // Attempting to override 'drive()' would cause a compile-time error
    // void drive() {
    //     System.out.println("Car is driving.");
    // }
 
    // Overriding the start() method
    @Override
    void start() {
        System.out.println("Car started.");
    }
}
 
public class VehicleDemo {
    public static void main(String[] args) {
        Vehicle v = new Vehicle();
        v.start(); // Vehicle started.
        v.drive(); // Vehicle is driving.
 
        System.out.println();
 
        Car c = new Car();
        c.start(); // Car started. (overridden method)
        c.drive(); // Vehicle is driving. (final method cannot be overridden)
    }
}