Can a generic class extend another class?

Can a generic class extend another class?

A generic class in Java can extend another class, including generic and classes. However, there are some restrictions and considerations when extending generic, especially regarding type parameters and constructors.

generic class

1. Extending Non-Generic Classes

If the superclass the subclass can be either generic or non-generic. In this case, the subclass does not inherit the type parameter(s) of the superclass.

2. Extending Generic Classes

If the superclass is a generic, the subclass can also be generic, and it can inherit the type parameter(s) from the superclass. However, the subclass can choose to specify its own type parameter(s) or use the type parameter(s) inherited from the superclass.

3. Type Parameter Compatibility

When extending a generic, the subclass’s type parameter(s) must be compatible with the type parameter(s) of the superclass. This ensures type safety and allows the subclass to maintain the contract defined by the superclass.

Example
java
// Non-generic superclass
class Box {
    private Object value;

    public Box(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }
}

// Generic subclass extending a non-generic superclass
class GenericBox<T> extends Box {
    public GenericBox(T value) {
        super(value); // Call to superclass constructor
    }
}

// Generic superclass
class Container<T> {
    private T item;

    public Container(T item) {
        this.item = item;
    }

    public T getItem() {
        return item;
    }
}

// Generic subclass extending a generic superclass
class CustomContainer<T> extends Container<T> {
    public CustomContainer(T item) {
        super(item); // Call to superclass constructor
    }
}

public class GenericClassExtensionExample {
    public static void main(String[] args) {
        // Create instances of GenericBox and CustomContainer
        GenericBox<String> genericBox = new GenericBox<>("Java");
        CustomContainer<Integer> customContainer = new CustomContainer<>(42);

        // Get values from instances and print them
        String value1 = (String) genericBox.getValue();
        Integer value2 = customContainer.getItem();

        System.out.println("Value from GenericBox: " + value1);
        System.out.println("Value from CustomContainer: " + value2);
    }
}

In this example

, GenericBox is a generic class that extends the non-generic Box. The GenericBox class inherits the value field and methods from the Box class. Similarly, CustomContainer is a generic that extends the generic Container, inheriting the item field and methods from the Container class. Both subclasses demonstrate how can extend another class, either generic or non-generic, in Java.

Homepage

Readmore