Java-Method-Overriding-Overloading

Java Implements the Polymorphisim in one of the two ways that is Method Overriding and Method Overloading

 

Method Overriding :

Method overriding occurs when sub class declares a method that has the same signature (name, plus the number and the type of its parameters) and return type as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior thatfs specific to a particular subclass type. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type. Which overridden version of the method to call is decided at runtime based on the object type.

 

The rules for overriding a method are as follows:

  •  The argument list must exactly match that of the  overridden method. If doesn't match we will get a overloaded method not a overriding method.
  • The return type must be same as, or a subtype of, the return type declared in the original overridden method in the superclass.
  •  We can not override method marked final. Static methods can't be overridden but they can be   redefined.
  • If a method can't be inherited , you cannot override it. Overriding is nothing but we are reimplementing a method  that we are inherited
  • Overriding method must not throw checked exceptions that are new and broader than the those declared by the overridden method
  • The access level can't be more restrictive than the overridden method. It can be less restrictive than that of overridden method
  • The overriding method can throw any unchecked or runtime  exception, regardless of weather overridden method declares the exception or not.
  •  The overbidding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected.
  • Constructors cannot be overridden.

 

A program to explain the above rules of Java Method Overridding

 

public  class SuperClass{

 

         public void method1() {

                System.out.println("SuperClass.method1()");

         }

        

         private void method2() {

                System.out.println("SuperClass.method2()");

         }

         public final void method3(){

                System.out.println("SuperClass.method3()");

         }

          private final void method4(){

                System.out.println("SuperClass.method4()");

         }

        

         public static void method5() {

               System.out.println("SuperClass.method5()");

         }

        

         public void method6() throws Exception {

                System.out.println("SuperClass.method6()");

         }

        

         private void method7(){

                System.out.println("SuperClass.method7()");

         }

        

         private void method8(int x){

                System.out.println("SuperClass.method8()");

         }

        

         public static void method9() {

               System.out.println("SuperClass.method9()");

         }

}

public class SubClass extends SuperClass {

      

         public void method1() {

                System.out.println("OverridingClass.method1()");

         }

         private void method2(){

                System.out.println("OverridingClass.method2()");

         }

         //We can't override a public final method

         /*     public final void method3(){          

                       System.out.println("OverridingClass.method3()");

                }*/

        

         private final void method4(){

                System.out.println("OverridingClass.method4()");

         }

        

         public static void method5() {

               System.out.println("OverridingClass.method5()");

         }

        

         public void method6() throws IOException{

                System.out.println("OverridingClass.method6()");

         }

        

         public void method7(){

                       System.out.println("OverridingClass.method7()");

         }

        

         public void method8(final int x){

                System.out.println("OverridingClass.method8()");

         }

        

         //A static method cannot be overridden to be non-static instance method

         /*public void method9() {

               System.out.println("OverridingClass.method9()");

         }*/

        

}

public class MethodOverrdingSample{

       public static void main(String[] args) {

           SubClass sub = new SubClass();

           SuperClass sc = new SubClass();

           sub.method1();

           sub.method3();

           /*   Since its private, the below 2 methods are not visible

           sub.method2();

           sub.method4();*/

          

           sub.method5();

           try {

                     sub.method6();

              } catch (IOException e) {

                     e.printStackTrace();

              }

           sub.method7();

           sub.method8(100);

           sc3.method5();

 

          SubClass subClass = new SubClass();

         SuperClass supClass = (SuperClass)subClass;

         supClass.method5();                   

         supClass.method1();

 

       }

}

 

To invoke a superclass version of overridden method we use a super keyword. For example

            public class Superclass{

                        public void method1(){

                                    System.out.println(gSuperclass Versionh);}

                        }

            }

            public class SubClass{

                        public method1(){

                                    super.method1();       //Invoke first superclass code

                                                                        //then do the subclass specific code

                                    System.out.println(gSubclass Versionh);

                        }

            }

Method Overloading :

Method overloading means  to have two or more methods with same name  in the same class and its subclass with different arguments and optionally different return type. Which overloaded version of the method to be called is based on the reference type of the argument passed at compile time.

 

The rules for overloading  a method are as follows:

 

šL  Overloaded methods must change the argument list.

šL  Overloaded methods can change the return type.

šL  Overloaded methods can declare new or broader checked exacpetions

šL  Overloaded methods can change the access modifier.

šL  Constructors can be overloaded.

 

A program to explain the above rules of Java Method Overloading

 

public class A {

       protected A(){

              System.out.println("Hi A Constructor");

       }

       public A(int i,int j){

              System.out.println("Hi A Constructor A,B");

       }

       public void method1(int i){

              System.out.println("Hi A in method1(i)");

       }

 

}

public class B extends A{

       public B(){

              System.out.println("Hi B Constructor");

       }

       public B(int i, int j){

              super(i,j);

              System.out.println("Hi B Constructor with i,j");

       }

       public void method1(int j){

              System.out.println("Hi B in method1(i)");

             

       }

       public void method1(int i, int j){

              System.out.println("Hi B in method1(i,j)");

       }

}

public class C extends A{

       public C(){

              System.out.println("Hi C Constructor");

       }

       public C(int i, int j){

              super(i,j);

              System.out.println("Hi C Constructor with i,j");

       }

       public void method1(int j){

              System.out.println("Hi C in method1(i)");

       }

      

       public void method1(int i, int j){

              System.out.println("Hi C in method1(i,j)");

       }

}

public class D {

              public  static void main(String[] args) {

              // TODO Auto-generated method stub

              int k=0;

              int l=0;

              A a=new A();

              B b= new B();

              a= b;

              C c= new C();

              A ac=c;

              a.method1(k);

              b.method1(k,l);

              b.method1(k);

              c.method1(k);

       /*ac.method1(k,l);*/ //Compiler erroe! Compiler looks only at the                                               reference and sees that Class A does not have                                            method1(int,int) method. Compiler doesn't care                                      about the actual object at runtime

                          

       }

 

}

 

Output for the above program

Hi A Constructor

Hi A Constructor

Hi B Constructor

Hi A Constructor

Hi C Constructor

Hi B in method1(i)

Hi B in method1(i,j)

Hi B in method1(i)

Hi C in method1(i)

 




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)