kirran

Wednesday, June 13, 2012

Overriding and Hiding Methods












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);
         
//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)

Instance Methods

                      An instance method in a subclass with the same signature and return type as an instance method in the superclass overrides the superclass's method.The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error.


Class Methods

If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass.

let us see the following example


public class Person {

void drive()

{

    System.out.println("we are iin person class");  }

}

class Father extends Person {

    void drive()
    {
        System.out.println("father drives smmothly yar");}
    }

class Son extends Father {

        void drive()
        {
            System.out.println("Son drives roughly yar"); }
        }

class Overridedemo extends Son {

public static void main(String[] args) {

    Person P = new Person();
    Father F = new Father();
    Father S = new Son();
    P.drive();
    P = F;
    P.drive();
    P=S;
    P.drive();
}
}




14 comments:

  1. Enjoyed reading this article throughout.Nice post! Digital Marketing is the trendy course right now and is going to be in
    a great demand in near future as jobs for this domain will be sky rocketted.To be on par with the current trend we have to
    gain complete knowledge about the subject. For the complete course online
    360Digitmg Digital Marketing Course

    ReplyDelete
  2. You have a good point here! I totally agree with what you have said !! Thanks for sharing your views ... hope more people will read this article  먹튀검증커뮤니티

    ReplyDelete
  3. I am definitely enjoying your website. You definitely have some great insight and great stories. buy website traffic

    ReplyDelete
  4. Easy option to get useful information as well as share good stuff with good ideas and concepts 먹튀폴리스

    ReplyDelete
  5. Thank you for the update, very nice site.. 토토검증

    ReplyDelete
  6. Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon. 스포츠토토

    ReplyDelete
  7. Thanks for sharing such information with us due to which my several concepts have been cleared.  먹튀폴리스

    ReplyDelete
  8. Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has the same topic with your article. Thanks, great share 메이저사이트

    ReplyDelete
  9. Compre documentos en línea, documentos originales y registrados.
    Acerca de Permisodeespana, algunos dicen que somos los solucionadores de problemas, mientras que otros se refieren a nosotros como vendedores de soluciones. Contamos con cientos de clientes satisfechos a nivel mundial. Hacemos documentos falsos autorizados y aprobados como Permiso de Residencia Español, DNI, Pasaporte Español y Licencia de Conducir Española. Somos los fabricantes y proveedores de primer nivel de estos documentos, reconocidos a nivel mundial.

    Comprar permiso de residencia,
    permiso de residenciareal y falso en línea,
    Compre licencia de conducir en línea,
    Compre una licencia de conducir española falsa en línea,
    Comprar tarjeta de identificación,
    Licencia de conducir real y falsa,
    Compre pasaporte real en línea,

    Visit Here fpr more information. :- https://permisodeespana.com/licencia-de-conducir-espanola/
    Address: 56 Guild Street, London, EC4A 3WU (UK)
    Email: contact@permisodeespana.com
    WhatsApp: +443455280186

    ReplyDelete
  10. Very good points you wrote here..Great stuff…I think you’ve made some truly interesting points.
    먹튀검증

    ReplyDelete