Wednesday, November 25, 2009

Key Java Concepts IV - Overridden Methods Basics

Today, we'll learn more about overridden methods. We can override a method when a subclass inherits a method from its superclass. The main advantage of overriding is that we can define the behavior that's specific to a particular class. We need to observe certain important rules while overriding methods.

  • The overriding method needs to have the exact argument list as the overridden method. By not doing so, we could get an overloaded method instead. 
  • The overridden method should have the same return type as the overridden method.

  • "final" methods cannot be overridden.

  • The access level of overriding method CANNOT be more restrictive than the overridden method.

  • The access level CAN be lesser restrictive than its overridden method.
  • We cannot override "static" methods.
  • The overriding method CAN throw any number of unchecked runtime exceptions, even if it isn't declared in the overridden method.
  • The overriding method CANNOT throw the checked exceptions which haven't been declared in the overridden method.
  • However, the overriding method CAN throw lesser or narrower checked exceptions than those declared in the overridden method.
  • A subclass in a different package can override methods marked public or protected. But make sure the methods are not marked final or static.

  • The overriding method CANNOT have a more restrictive access modifier than the overridden method. i.e you cannot override a public method and mark it protected.
  • The overriding method must not declare a exception it will never throw.

  • A method can be overridden only if it can be inherited.
Illustration:

public class Car {
         public Tyre() {
                  System.out.println("Common Car Tyre");
        }
}

public class Camaro extends Car {
        public Tyre() {
                System.out.println("Special Camaro tyres");
       }

}


Stumble Upon Toolbar

No comments:

Post a Comment

Related Posts with Thumbnails