Back to Top

Monday 16 September 2013

JAVA: Overloading and Overriding

Overloading:  


  Overloading is a popular technique of object oriented programming. It allows you to define a method with same name but with different parameters list.
 

 Java identifies method by its name and signature. So, if the combination of method name and signature is unique, the compiler doesn’t have any issue to identify it. When you use overloaded methods, the java compile will automatically identifies the right version of the method by number and/or types of passing parameters. But you can’t declare more than one method with same name and passing parameters. The compiler doesn’t consider return types when validating uniqueness of a method. That means you can’t have two methods with same name and passing parameters with different return type.

   Java allows both method and constructor overloading. Let’s see this with an example.

Code:

package com.interview.question.java;

public class OverloadingDemo {
     
  /**
    *
    * This class demonstrates overloading in java
    *
    * @author http://interviewquestionjava.blogspot.com
    *
    **/
     
      private int a;
     
      /* constructor overloading */
      public OverloadingDemo(){
           
      }
      public OverloadingDemo(int a){
           
            this.a = a;
           
      }
     
     
      /* method overloading */
      public int add(int num){
           
            a +=num;
           
            return a;
      }
      public int add(String str){
           
            a+= Integer.valueOf(str);
           
            return a;
      }
      public int add(int num1, int num2){
                 
                  a += num1;
                  a += num2;
                 
                  return a;
            }


      /* test overloading */
      public static void main(String[] args) {
     
            OverloadingDemo objOverloadingDemo1 = new OverloadingDemo();
            OverloadingDemo objOverloadingDemo2 = new OverloadingDemo(5);
           
            System.out.println(objOverloadingDemo1.add(5));
            System.out.println(objOverloadingDemo1.add("3"));
            System.out.println(objOverloadingDemo1.add(3, 5));
           
            System.out.println("-----");
           
            System.out.println(objOverloadingDemo2.add(5));
            System.out.println(objOverloadingDemo2.add("3"));
            System.out.println(objOverloadingDemo2.add(3, 5));
           
     
    }


}

Output:

5
8
16
-----
10
13
21


   Here, in this class OverloadingDemo we defined two constructors with different signatures, and three methods with same name but different number and/or types of passing parameters.


Overriding:


     Overriding is the technique of inheriting a class and redefining the behaviors of the super class. That means, when you define a method in subclass with the same signature (name, plus the number and the type of its parameters) and return type as in the superclass, then you are overriding the method of the superclass in your subclass, and the technique is known as method overriding.
   

           In method overriding, method name, method input parameters and return types in subclass should be same in superclass.  It can only modify the behaviors. It can return a subtype of the original return type defined in superclass, and this technique is known as covariant return type [Java 1.5 or above support this]. For example, suppose the return type in superclass is java.util.Map, you can change it to java.util.HashMap in subclass, as HashMap is a subtype of Map.

           You can also use @Override annotation [which is available in Java 1.5 or above] to tell the compiler that you are trying to override a method in the superclass. And, fof any reason, if the compile is unable to detect that method, it will generate an error.

            In method overriding in java, you can level up the access level but you can’t level it down. That means, if a method is declared as protected in superclass, it can be set as public is subclass but not as private.

             If a method is declared as final, it can’t be overridden.

Now let’s see with an example.

Code:

Super Class :


package com.interview.question.java;

import java.util.HashMap;
import java.util.Map;

public class SuperClass {
     
      /**
    *
    * This is a sample class
    *
    * @author http://interviewquestionjava.blogspot.com
    *
    **/
     
      /* the return type of this method is Map and in subclass it will be changed to HashMap */
      public Map methodForcovariant(){
            Map map = new HashMap();
            return map;
      }
     
      /* sample method which willbe overridden in subclass */
    public void sampleMethod(){
      System.out.println("SuperClass.sampleMethod()");
    }
   
    /* the specifier of this method willbe changed to public from protected in its subclass */
    protected void protectedMethod(){
      System.out.println("SuperClass.protectedMethod()");
    }
   
    /* this method can't be overridden as it's declare as final */
    public final void finalMethod(){
      System.out.println("SuperClass.finalMethod()");
    }

}

Sub Class:


package com.interview.question.java;

import java.util.HashMap;
import java.util.Map;


            public class OverridingDemo extends SuperClass{

                  /**
                *
                * This class demonstrates overriding by extending SuperClass
                *
                * @author http://interviewquestionjava.blogspot.com
                *
                **/
                 
                  /* Overriding with covariant return type :
                   * the return type of this method is modified to its subtype which is allowed in method overriding */
                  @Override
                public HashMap methodForcovariant(){
                        HashMap hmp = new HashMap();
                        return hmp;
                  }
                 
                  /* Overriding:
                   * overriding the method SuperClass.sampleMethod() */
                  @Override
                  public void sampleMethod(){
                  System.out.println("OverridingDemo.sampleMethod()");
                }
                 
                 
                  /* Overriding access specifier:
                   * the specifier of this method is changed to public from protected */
                  @Override
                public void protectedMethod(){
                  System.out.println("OverridingDemo.protectedMethod()");
                }
                 

           
            public static void main(String[] args) {
                 
                  SuperClass objSuperClass = new SuperClass();
                  SuperClass objOverridingDemo = new OverridingDemo();

                  objSuperClass.sampleMethod();

                  objOverridingDemo.sampleMethod();
                 
            }
                 
     
}

Output:

SuperClass.sampleMethod()
OverridingDemo.sampleMethod()


Here, we have used 4 methods:
methodForcovariant() – it shows the change of return type to its subtype during method overriding.
sampleMethod() – it shows method overriding in normal way.
protectedMethod() – it shows method overriding by leveling up access specifiers.
finalMethod() – it shows we can’t override methods declared as final.






10 Responses to “ JAVA: Overloading and Overriding ”

Anonymous said...
16 September 2013 at 13:07

nice post


Anonymous said...
31 December 2013 at 13:14

thanks!


hitesh kumar said...
12 January 2016 at 07:33

Method Overriding in Java

Thanks for this post, keep sharing


SEO Services said...
22 November 2017 at 13:16

It’s a very informative and helpful article, thank you for sharing!



CIITNOIDA - Best Oracle and linux training institute in noida delhi ncr said...
28 June 2018 at 16:34

Best MCA

colleges in noida

Best MSC IT

colleges in noida

Best M

TECH colleges in noida


Praveen H said...
29 October 2018 at 00:00

nice article, very informative.
for java interview programs visit: Java programming


Unknown said...
8 November 2018 at 15:08

Very useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
kindle mobi conversions


abc said...
14 August 2019 at 01:26


I learn a lots of things here. It is an amazing post , thanks for help me.
students can learn programming on python programming tutorial
java programming language
cpp programming language


Hitesh Kumar said...
10 May 2020 at 22:56

method overloading in java
Really nice your article thanks for sharing this article


MLSU BA 1st Year Exam Result 2021 said...
21 May 2022 at 21:11

Really great article, Glad to read the article. It is very informative for us. Thanks for posting.


Post a Comment

Popular Posts

All Rights Reserved JAVA INTERVIEW QUESTIONS | Privacy Policy | Anijit Sarkar