Java Method Overriding.

Java Method Overriding

  • You Override a method in a super-class when you define a method in a class with exactly the same name and signature as an existing method in a super-class.
  • The return type defined for the method does not affect this.
  • A common programming error in Java is to accidentally overload a method when trying to override it.
  • An annotation syntax (@Override) provides a means for the compiler to understand this.
    class Cat extends Mammal {
      @Override
      void sleep( ) { ... }
    }
         
  • Overridden methods, on the other hand, are selected dynamically at runtime.
  • You cannot override a static method with an instance method.
    (static method in a super-class can be shadowed by another static method in a sub-class)
  • You can use the final modifier to declare that an instance method can't be overridden in a subclass.
  • For a method to qualify as an overridden method in a subclass, it must have exactly the same numbers and types of arguments.
  • When you override a method, you may change the return type to a subtype of the original method's return type.
  • Method overriding is normally used to achieve polymorphism, which is to execute the right object method even the reference is of base class type.
    Method Overriding example:
    class Animal{
       public String move(){
          return "Animals can move";
       }
    }
    class Cow extends Animal{
       @Override
       public String move(){
         return "Cow can walk and run";
       }
    }
    
    public class OverridingMethods {
        public static void main(String args[]){
          Animal a = new Animal();      // Animal reference to an Animal object
          Animal b = new Cow();         // Animal reference to a Cow object
          System.out.println(a.move()); // Runs the method in Animal class
          System.out.println(b.move()); // Runs the method in Cow class
       } 
    }
    The result of this is:
    Animals can move
    Cow can walk and run
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.