Java Method Overriding: Runtime Polymorphism in Subclasses

package Pack1;

class my_first {
    public void games() {
        System.out.println("Cricket ( parent )");
    }
    public static void main(String[] args) {
        my_first obj1 = new my_first();
        obj1.games();  // Calls parent method -> Cricket ( parent )

        my_first obj2 = new game_types();
        obj2.games();  // Calls overridden child method -> Football ( child )
    }
}

class game_types extends my_first {
    @Override
    public void games() {
        System.out.println("Football ( child )");
    }
}

Output:

Cricket ( parent )
Football ( child )

1. Five Compiler Rules for Method Overriding in Java 🔝

Rule Requirement Why It Matters
Inheritance (extends) Parent → Child class Overriding only occurs across a superclass/subclass or interface relationship.
Method Signature Exact same name & parameters Changing parameter types overloads the method instead of overriding it.
Access Visibility Same or wider A public parent method cannot be overridden as protected or package-private.
final & static Cannot be overridden final locks the method; static methods bind to the class at compile time.

2. Example 2: Overriding Inherited Methods & Adding New Child Methods 🔝

In addition to overriding games(), the child class game_types can define its own specialized method indoor_games(). Note that calling indoor_games() requires a reference of type game_types (obj3):

package Pack1;

class my_first {
    public void games() {
        System.out.println("Cricket ( parent )");
    }
    public static void main(String[] args) {
        my_first obj1 = new my_first();
        obj1.games();

        my_first obj2 = new game_types();
        obj2.games();

         // Child-specific method indoor_games() requires a game_types reference:
        game_types obj3 = new game_types();
        obj3.indoor_games();
    }
}

class game_types extends my_first {
    @Override
    public void games() {
        System.out.println("Football ( child )");
    }
    public void indoor_games() {
        System.out.println("Table Tennis ( child )");
    }
}

Terminal Output:

Cricket ( parent )
Football ( child )
Table Tennis ( child )

3. Invoking the Overridden Parent Method with super.games() 🔝

If a child class wants to extend the parent method's behavior rather than completely replacing it, call super.games() inside the overriding child method:

class ParentGame {
    public void games() {
        System.out.println("1. Cricket (from ParentGame)");
    }
}

public class ChildGame extends ParentGame {
    @Override
    public void games() {
        super.games();  // Invokes parent implementation first!
        System.out.println("2. Football (added by ChildGame)");
    }
    public static void main(String[] args) {
        new ChildGame().games();
    }
}

Terminal Output:

1. Cricket (from ParentGame)
2. Football (added by ChildGame)

4. Why final and static Methods Cannot Be Overridden 🔝

  • final void games(): Marking a parent method final forbids any subclass from overriding it (trying to declare public void games() in game_types produces a compile error: games() in game_types cannot override games() in my_first; overridden method is final).
  • static methods (including main()): Static methods belong to the class, not to individual objects. Defining a static method with the same signature in a subclass hides the parent method at compile time rather than overriding it at runtime:
class BaseLogger {
    static void banner() { System.out.println("Base static banner"); }
    void instanceLog()   { System.out.println("Base instance log"); }
}

class SubLogger extends BaseLogger {
    static void banner() { System.out.println("Sub static banner (hidden, NOT overridden!)"); }
    @Override
    void instanceLog()   { System.out.println("Sub instance log (overridden at runtime!)"); }
}

public class StaticVsDynamicDispatch {
    public static void main(String[] args) {
        BaseLogger ref = new SubLogger();
        ref.banner();       // Resolved by reference type (BaseLogger) at compile time!
        ref.instanceLog();  // Resolved by actual object (SubLogger) at runtime!
    }
}

Terminal Output:

Base static banner
Sub instance log (overridden at runtime!)

5. Covariant Return Types in Overridden Methods (Java 5+) 🔝

An overriding child method can return a more specific subclass of the parent method's return type (for example, returning Integer when the parent returns Number):

class ShapeFactory {
    Number getScale() { return 1; }
}

public class CircleFactory extends ShapeFactory {
     // Covariant return type: Integer is a subclass of Number!
    @Override
    Integer getScale() { return 10; }

    public static void main(String[] args) {
        System.out.println("Covariant scale: " + new CircleFactory().getScale());
    }
}

Terminal Output:

Covariant scale: 10

6. Comparison: Method Overriding vs Method Overloading 🔝

Feature Method Overriding Method Overloading
Class Scope Parent & Child class (extends) Same class (or inherited)
Parameter List Must be identical Must be different
@Override Annotation Recommended (verified by compiler) Not allowed (compile error)
Resolution Time Runtime (based on actual object) Compile-time (based on reference type)

7. Practical Recipe: Overriding Object.toString() for Clean Printing 🔝

Every Java class implicitly extends java.lang.Object. Overriding public String toString() lets System.out.println(p) print human-readable object fields instead of a memory hash like PlayerProfile@15db9742:

public class PlayerProfile {
    String name;
    int runs;
    PlayerProfile(String name, int runs) { this.name = name; this.runs = runs; }

    @Override
    public String toString() {
        return "PlayerProfile[name=" + name + ", runs=" + runs + "]";
    }
    public static void main(String[] args) {
        PlayerProfile p = new PlayerProfile("Virat", 120);
        System.out.println(p);  // Automatically calls overridden toString()!
    }
}

Terminal Output:

PlayerProfile[name=Virat, runs=120]

8. Common Developer Pitfalls & Traps 🔝

Accidental Spelling or Parameter Mismatch Without @Override

If you accidentally write public void game() (singular) instead of games() in game_types without the @Override annotation, the code compiles silently as a brand-new method and obj2.games() still calls the parent method! Always add @Override so the compiler flags typos immediately.

Reducing Access Visibility in the Subclass

If the parent method is public void games(), writing void games() (package-private) in game_types fails to compile. An overriding method can widen access (e.g., protected → public) but can never narrow it.

9. Complete Compilable Java Program 🔝

public class OopOverridingFullDemo {
    static class Base { int rate() { return 5; } }
    static class Premium extends Base {
        @Override int rate() { return super.rate() + 3; }
    }
    public static void main(String[] args) {
        Base b = new Premium();
        if (b.rate() == 8) {
            System.out.println("All Java method overriding checks passed! rate=8");
        }
    }
}

Terminal Output:

All Java method overriding checks passed! rate=8

10. Frequently Asked Questions (FAQ) 🔝

Can private methods be overridden in a child class?

No. Because private methods are invisible to subclasses, declaring a method with the same name in a child class creates an unrelated new method (and adding @Override will cause a compile error).

Can constructors be overridden in Java?

No. Constructors are not inherited by subclasses; a constructor's name must always match its own class name, and parent constructors are invoked via super(...).

Why did my_first obj2 = new game_types(); call the child's games() method?

Because Java uses dynamic method dispatch (runtime polymorphism) for non-static methods: the JVM checks the actual heap object type (game_types) at runtime rather than the variable's declared type (my_first).

What Checked Exceptions can an overriding method throw?

An overriding method can throw the same checked exceptions as the parent method, a narrower subclass of those exceptions, or no exceptions at all—but it cannot throw a broader new checked exception.

Are instance variables (attributes) overridden like methods?

No! Instance fields in Java are resolved at compile time based on the reference type (field hiding), not at runtime. Always use methods for polymorphic behavior.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer