Thursday 24 October 2019

Static methods


  1. Java interface static method is similar to default method except that we can’t override them in the implementation classes.
  2. They are part of interface, we can’t use it for implementation class objects.
  3.  It helps in providing security by not allowing implementation classes to override them.
  4.  Interface static methods by-default not available to the implementation classes hence by using             implementation class reference we can’t call interface static  Method.
  5. We should call interface static methods by using interface name.
            Example 1.

                   interface Static
                    {  
                              public static void sum(int a, int b)
 {  
                                         System.out.println("The Sum:"+(a+b));  
                              }  
 }  
                   class Test implements Static{  
                             public static void main(String[] args)
{   
                                           Test t = new Test();                     
t.sum(10, 20); //Compile Time Error                     
                                          Test.sum(10, 20); //Compile Time Error
                                          Static.sum(10, 20);       
                              }
                      }

            Example 2.
               interface Static{       
                       public static void m1() {} }
               class Test implements Static{  
                     public static void m1() {}  }
               It’s valid but not overriding

             Example 3.
                   interface Static
                  {  
                      public static void m1() {}  
                  }  
                  class Test implements Static
                 {  
                     public void m1() {}  
                 }    
                             This’s valid but not overriding

            Example 4.
           class P{  
                          private void m1() {}  
                      }  
            class C extends P {  
                    public void m1() {}  
                     }  
                              This’s valid but not overriding

               From 1.8 version onwards we can write main() method inside interface and hence  we can run             interface directly from the command prompt.


              Example : 5
 interface Static{  
      public static void main(String[] args) {  
                System.out.println("Interface Main Method");    
       }  
 }

Example :6.  How to call static method in Functional Interface using java 8


Output:- Static Method











Share this

2 Responses to "Static methods"

  1. What a nice blog to learn java 8! Kudos to your efforts :)

    ReplyDelete