Programmer's Rules


Overriding and Overloading In Java

Collected rules of overriding and overloading in Java in a concise way

Javajob interviewOCA

Basic rules

- Methods can be overridden or overloaded; constructors can be overloaded but not overridden.

- Abstract methods must be overridden by the first concrete (non-abstract) subclass.

- With respect to the method it overrides, the overriding method:

  * Must have the same argument list.

  * Must have the same return type, except that as of Java 5, the return type can be a subclass—this is known as a covariant return.

  * Must not have a more restrictive access modifier.

  * May have a less restrictive access modifier.

  * Must not throw new or broader checked exceptions.

  * May throw fewer or narrower checked exceptions, or any unchecked exception.

- final methods cannot be overridden.

- Only inherited methods may be overridden, and remember that private methods are not inherited.

- A subclass uses super.overriddenMethodName() to call the superclass version of an overridden method.

- Overloading means reusing a method name, but with different arguments.

- Overloaded methods

  * Must have different argument lists

  * May have different return types, if argument lists are also different

  * May have different access modifiers

  * May throw different exceptions

- Methods from a superclass can be overloaded in a subclass.

- Polymorphism applies to overriding, not to overloading.

- Object type (not the reference variable's type), determines which overridden method is used at runtime.

- Reference type determines which overloaded method will be used at compile time.

Advanced Overloading

- Primitive widening uses the "smallest" method argument possible.

- Used individually, boxing and var-args are compatible with overloading.

- You CANNOT widen from one wrapper type to another. (IS-A fails.)

- You CANNOT widen and then box. (An int can't become a Long.)

- You can box and then widen. (An int can become an Object, via an Integer.)

- You can combine var-args with either widening or boxing.
Tutorial statistics