Overriding in Java refers to redefining a superclass method in a subclass. When using generics, overriding still follows the same rules, but type parameters can add flexibility or complexity.
Generic classes can:
- Inherit from other generic or non-generic classes
- Override methods with or without type parameters
- Add constraints via bounded types
Syntax
class SuperClass<T> {
public void display(T value) {
System.out.println("Super: " + value);
}
}
class SubClass<T> extends SuperClass<T> {
@Override
public void display(T value) {
System.out.println("Sub: " + value);
}
}Code language: JavaScript (javascript)
Program
class Printer<T> {
public void print(T value) {
System.out.println("Printer prints: " + value);
}
}
class FancyPrinter<T> extends Printer<T> {
@Override
public void print(T value) {
System.out.println("FancyPrinter prints *** " + value + " ***");
}
}
public class Demo {
public static void main(String[] args) {
FancyPrinter<String> printer = new FancyPrinter<>();
printer.print("LotusJavaPrince");
}
}
/*
FancyPrinter prints *** LotusJavaPrince ***
*/
Overriding With Bounded Type Parameters
class Calculator<T extends Number> {
public double square(T value) {
return value.doubleValue() * value.doubleValue();
}
}
class AdvancedCalculator<T extends Number> extends Calculator<T> {
@Override
public double square(T value) {
System.out.println("Advanced squaring: " + value);
return super.square(value);
}
}
public class MathTest {
public static void main(String[] args) {
AdvancedCalculator<Integer> calc = new AdvancedCalculator<>();
System.out.println("Result: " + calc.square(5));
}
}
/*
Advanced squaring: 5
Result: 25.0
*/Non-Generic Subclass Overriding Generic Method
class Employee<T> {
public void show(T id) {
System.out.println("Employee ID: " + id);
}
}
class PermanentEmployee extends Employee<String> {
@Override
public void show(String id) {
System.out.println("Permanent Employee ID: " + id);
}
}
public class TestEmp {
public static void main(String[] args) {
PermanentEmployee pe = new PermanentEmployee();
pe.show("EMP2025");
}
}
/*
Permanent Employee ID: EMP2025
*/5. Overriding Methods with Wildcards !!
You cannot override a method using a wildcard (like <?>) in place of a type parameter.
class Container<T> {
public void addItem(T item) { }
}
// Invalid: can't override using wildcard
// class NewContainer<T> extends Container<T> {
// public void addItem(?) { } // Not allowed Compile Time Error
// }Real-World Example: Bank Account
class Account<T> {
public void process(T details) {
System.out.println("Processing account: " + details);
}
}
class SavingsAccount extends Account<String> {
@Override
public void process(String details) {
System.out.println("Savings Account processed for: " + details);
}
}
public class BankSystem {
public static void main(String[] args) {
SavingsAccount acc = new SavingsAccount();
acc.process("LotusJavaPrince");
}
}
/*
Savings Account processed for: LotusJavaPrince
*/