Method Overriding & Overloading
Method Overriding
Example
// Basic Overriding Example
class Parent {
void show() { System.out.println("Parent method"); }
}
class Child extends Parent {
@Override
void show() { System.out.println("Child method"); }
}
// Overriding with Covariant Return Type
// The overridden method in the subclass can return a subtype of the superclass method’s return type.
class Parent {
Number getValue() { return 10; }
}
class Child extends Parent {
@Override
Integer getValue() { return 20; } // Covariant return type (Integer is a subtype of Number)
}
// Overriding with Exception Handling
// The overridden method cannot throw broader checked exceptions.
class Parent {
void method() throws IOException {}
}
class Child extends Parent {
@Override
void method() throws FileNotFoundException {} // Allowed (Narrower exception)
// void method() throws Exception {} // Not allowed (Broader exception)
}
// Hiding Static Methods (Not Overriding)
// Static methods are not overridden, they are hidden.
class Parent {
static void show() { System.out.println("Parent static method"); }
}
class Child extends Parent {
static void show() { System.out.println("Child static method"); }
}
// Final Methods Cannot Be Overridden
class Parent {
final void show() { System.out.println("Final method"); }
}
class Child extends Parent {
// void show() {} // Compilation error (Cannot override final method)
}
// Using super to Call Parent Method
class Parent {
void show() { System.out.println("Parent method"); }
}
class Child extends Parent {
@Override
void show() {
super.show(); // Calls the parent method
System.out.println("Child method");
}
}
// Incorrect use of @Override
class Parent {
void method(int a) {}
}
class Child extends Parent {
// @Override void method(double a) {} // Compilation error (Not the same signature)
}
// Private methods cannot be overridden (they are not inherited)
class Parent {
private void secret() {}
}
class Child extends Parent {
void secret() {} // This is a new method, NOT an override
}
// Illegal Case (Incompatible Covariant Type)
class Parent {
Number getValue() {
return 10;
}
}
class Child extends Parent {
@Override
String getValue() { // Compilation error: String is NOT a subclass of Number
return "Error";
}
}Method Overloading
Example
Overloading by Only Return Type ?
Example Case
What If Return Type Was Considered?
Last updated