+91 81900 98289

Java Overriding

Overriding replaces a superclass method with a version that fits the subclass. The name, parameters, and return type must match. Put @Override above the method so the compiler checks that a superclass method really exists.

The method that runs depends on the object's actual class, not the type of the variable. A Person variable that points at a Mentor still runs Mentor's version.

Example

The variable type is Base, but the object is a Lead. role() uses the override and prints mentor.

class Base { String role() { return "person"; } } class Lead extends Base { @Override String role() { return "mentor"; } } public class Dispatch { public static void main(String[] args) { Base who = new Lead(); System.out.println(who.role()); } }
Overloading picks a method at compile time from the argument types. Overriding picks a method at run time from the object. They solve different problems.