3. You want to have only a single piece of storage for a particular field, regardless of how many objects of that class are created, or even if no objects are created. You need a method that isn’t associated with any particular object of this class. That is, you need a method that you can call even if no objects are created. Need for static members
4. When you say something is static, it means that particular field or method is not tied to any particular object instance of that class So even if you’ve never created an object of that class you can call a static method or access a static field. With non-static fields and methods, you must create an object and use that object to access the field or method, since non-static fields and methods must know the particular object they are working with. Java guys use the terms class data and class methods, meaning that the data and methods exist only for the class as a whole, and not for any particular objects of the class. Since static methods don’t need any objects to be created before they are used, they cannot directly access non-static members or methods by simply calling those other members without referring to a named object (since non-static members and methods must be tied to a particular object static
5. class StaticTest { static inti = 47; } StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); Both st1.i and st2.i have the same value of 47 since they refer to the same piece of memory. Accessing static fields Use reference Use class name – StaticTest.i Static fields
6. class Incrementable { static void increment() { StaticTest.i++; } } Incrementablesf = new Incrementable(); sf.increment(); Static method
7. Create a Java class with the static main method Declare a static integer field and set it to 30 Create a static method which increments this field and prints it Create a non static method which prints the value in the static integer field Try to remove the print in the static method and call the non static method instead Exercise