Deciding whether something should be static

Static should be applied to:

  • A variable or method that is independent of the specific instance of the class
  • When a method performs a task that is independent of the contents of the object
  • Examples:

  • Every square has it’s own area, which is composed of unique length * height of that particular square instance, therefore area is an instance method as this method depends on unique length and height measurement unique to that object
  • Every square has it’s own area, which is composed of unique width * height of that particular square instance, therefore the width and height would be instance variables (they differ for each object)
  • The method in the Math class DO NOT depend on a specific instance of a class, therefore these methods are static methods
  • Static imports allow us to access static variables and static methods without typing the class name

    To access a static variable or static method, we can use:

    [Classname].[static variable name]

    or

    [Classname].[static method name]

    We can import using:

    import static java.lang.Math.*

    this means, import all the static variables and static methods inside the Math class and allows us to say things like

    double t= sqrt(PI); // instead of

    double t= Math.sqrt(PI);

    e.g.

    import static java.lang.System.*;
    import static java.lang.Math.*;
    
    public class Test {
    	
    	public static void main(String[] args)
    	{
    		double t=sqrt(PI); // instead of Math.sqrt(PI)
    		out.println(t); // instead of System.out.println(t)
    		
    	}
    }
    

    Output:

    1.7724538509055159

    Good video on how static and non static variables and methods interact with each other.

    Static can call non static, no problems. But static cannot call non static without the create of an object. Static lives in the world of none objects. However, non static CAN call static directly.

    Leave a Reply