Saturday, June 14, 2014

Learning Java - What does the ‘static’ keyword mean?

Static means a variable of the class and not the object of a class.

For example:
public class StaticExample {
      public static String name = "noob.. I am a static variable";
}
We have another class where-in we intend to access this static variable just defined.
public class Application {
        public static void main(String[] args) {
            System.out.println(StaticExample.name)
        }
}
We don’t create object of the class StaticExample
to access the static variable. We directly use the class name itself: StaticExample.name

static has not state, so dont need an object

static method can be a constructor/

no need to create an object.

good for use in a factory - pass in params - get the correct object back.

disadvantage.

cant be used in interface. so kind of limiting functionality to implementation in the code.

Statics methods are good for things like singletons where access to the constructed object needs to be controlled.

No comments:

Post a Comment