Wednesday 29 February 2012

Use Static Method directly without using class name



One among lot of interesting things of  java is the use of static method , which is basically a class level method and shared by all instances

Mostly we end up using static methods by referencing class name and the require method like

                                           System.out.println(String.valueOf(true));

Other way provided by Java is STATIC IMPORTS

 Same above expression can be used as following (note : I haven't been using class name here i.e. String)


                                          System.out.println(valueOf(true));


To do this you need to add a static import  as

                                          import static java.lang.String.valueOf;

So the whole code would look like


               import static java.lang.String.valueOf;


              public class StaticTestClass {
   
                         public static void main(String args[])
                        {
                           System.out.println(valueOf(true));
                        }

              }



But , this isn't a good practice because

  1. As it leads to lot of confusion when your code goes big  and makes uderstanding trouble some
  2. Lets assume you have another class which also has valueOf as static method and they you do a static import of this custom class method . This would lead to compile time ambiguous error as compiler wont be able to know which actual method to use. Error would look like :
                 The method valueOf(boolean) is ambiguous for the type StaticTestClas

So Avoid it and use class name "." method name directly.

No comments:

Post a Comment