Sunday, 6 October 2013

Method overriding and overloading in Java

After going through inheritance now it is time to know about method overriding and overloading.
Method overloading terminology is used where method name is same but it may have different set of parameter list,same parameter with different order. Compile time binding is done for method overloading.

Some important points about method overloading :
  • Method overloading is same method name having different arg list,order withing the class.
  • Binding happens at compile time.
  • Overloaded method must have different sets of param or order or both.
  • Return type in method overloading does not matter as binding happens at compile time.
  • Static method can be overloaded.
Please loot at sample code of overloading :

public class Overload {


    void fun()
    {
      
    }
   
    void fun(int a) //overloaded method of fun
    {
      
    }
}




 Now we will look into method overriding . Method overriding is the concept of overriding the parent method into the child class.
Following are the important points about overriding :


  • Overridden method  has same method signature of parent method.
  • If you mark final method in parent class then that can not be overriden.
  • Binding happens at run time. 
  • One more important point  is if your parent method has throws IOException in signature then in child class overridden method you used "throws Exception", then it shows compile time error .As you can either throw IOException or its child exception.
  • While overriding you can not minimize the visibility of overridden method. It means suppose you have declared public void fun() in your parent class and same method is overridden at child class having void fun() with no visibility mentioned (default) .In such case it throws compile time error.
To be more clear please look at following piece of code:


class Parent
{
    void printParent() throws IOException
    {
        System.out.println("In parent");
    }
}

class Child extends Parent
{
    void printParent() throws IOException
    {
        System.out.println("In child");
    }
}

 

No comments:

Post a Comment