Java default method and static method


 Java 8   introduce  default methods . 



  Feature 

  1.  Default  method  can be override  as given example show() method  override it.

  2.   Static  Method  of the  Interface  can be over ride .  But  if we try to  do so  the  
        static  method  class  will behave as  different  static method of the class .  As 

       You can  see  the  method call  in the  main() method .  They  call by  using  Interface
        and class object separately.  




  Example 

  The show() method  of the class no need to define . Only square() is defined.


interface TestIntf1

{ 

    // default method 

    default void show() 

    { 

        System.out.println("Default TestInterface1"); 

    } 

} 

  

interface TestIntf2 

{ 

    // Default method 

    default void show() 

    { 

        System.out.println("Default TestInterface2"); 

    } 

    

    

    public static void  statMe() {

    System.out.println("i am stat in interface ");

    }

} 


   



public class DefaultMethod  implements  TestIntf1 ,TestIntf2  {

public static void  statMe() {


    System.out.println("i am  stat in  DefaultMethodClasss");



    }


// Default emthod  override 

public void   show() {

 

TestIntf1.super.show();

TestIntf2.super.show();

 

 

 

}

 

public static void  main (String agrs[]) {

 

DefaultMethod d=new DefaultMethod();

                d.show();


 

DefaultMethod.statMe(); // Static  method of class  as different behave

         

TestIntf2.statMe();   // statMe() not override  as it is static 


     

}

   

}


 Program Output :

Default TestInterface1

Default TestInterface2

i am  stat in  DefaultMethodClasss

i am stat in interface 

Java default method and static method  Java default  method and static method Reviewed by Mukesh Jha on 8:30 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.