Rules for Overriding

  1. Only non-static visible instance methods can be overriden:

    • Private methods are not visible and hence not overriden.

    • Protected methods can be overriden by a subclass within the same package.

    • Static methods are not overriden, but they are inherited.

  2. When you refer to a child class object using a Parent reference (e.g.  Parent p = new Child()) and invoke a method, the overriden child class method will be invoked.

  3. The argument list must be same as that of the overridden method.

    • If they don't match, you might be doing an overload rather than override.

    • You can prevent accidental mistakes using the @Override annotation. 

      • Compiler will also throw error when @Override is applied on static methods, static variables or instance variables.

  4. In case of reference types (classes or interfaces), the return type must be the same as, or a subtype of the return type declared in the parent class method (also called covariant return type).

  5. In case of primitives, return types should be same; even int and short, or double and float, will give compilation error that: "The return type is incompatible with...".

  6. Final classes cannot be inheritted and final methods cannot be overriden.

  7. Constructors cannot be overridden.

  8. You cannot declare throws with new or wider checked exception

    • Can remove throws exception.

    • Can throw unchecked exception

  9. The overriding method must not have more restrictive access modifier.

    • Public cannot be made default, but a default can be made public.

  10. Can use the super keyword to invoke the overridden method from a subclass

  11. You can make a non-abstract method as abstract in child class; however child class should also be declared as abstract.

  12. The synchronized modifier and strictfp modifier has no effect on the rules of overriding.

Tags: 

Comments

I simply use @Override  annotation.. it will give error message at compile time... :)  so that we will check easily if any problems occur while overriding... :) :)

Was it useful?

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!