Sunday, 20 May 2012

Overriding Methods in Java – Basic Rules

 

What is Overriding  ?

When a class inherits a certain method from its parent class or superclass , that method can be overridden , unless it is marked final , private or static.

Basically overriding is done to make the method inherited , more class specific.

E.g.

Capture

Rules for overriding ~

  • The return type and the argument of the method defined in the super class should be same in the subclass (can be seen in the above example).
  • Private methods are not inherited , hence cannot be overridden.
  • Methods marked Final cannot be overridden. Had it been the case the keyword final would have lost it’s significance.
  • Static methods cannot be overridden they are hidden.

Consider the following Example:

Capture

The Output is :

Has Brakes

Has Disc Brakes

if we define main method as

Capture

The output is :

Has Brakes

Has Brakes

The following table summarizes what happens when you define a method with the same signature as a method in a superclass

Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides
  • While overriding we can only release the level of access of the method specified in the superclass or keep it the same. We CANNOT restrict the method further.

E.g.

If there is a protected method defined in the superclass and is inherited and is tried to be overridden with an access specifier less restricted than protected i.e. Private , then it will give a ERROR ! If it is overridden as a Public method or a Protected method it runs SUCCESSFULLY.

REMEMBER : Level of restriction ~

public < protected < default < private

4 comments:

  1. Thanks for providing information. Can you please explain about abstract classes and exception handling in your blog.

    ReplyDelete
  2. Sure . . in the coming blogs !

    ReplyDelete
  3. excellent…makes all things clear.

    ReplyDelete
  4. Nice blog, here I had an opportunity to learn something new in my interested domain about overriding concepts. I have an expectation about your future post so please keep updates.JAVA Course in Chennai

    ReplyDelete