10k

Static in Java

  1. Static fields

    • There is only one single copy of each static field.
    • It belongs to class not any individual object.
    • the fields are shared by all instances.
  2. static constants

    • What more common is static constan.
  3. static Methods

    • Methods that not operate on objects.

    • You can think it as it does not have a this parameter.

    • So it can only access static fields(because it does not operate on objects).

    • An object can invoke a static method. It's legal. But this can be confusing because the static method has no reletaive with the object.

      Use class name rather than objects to invoke static methods.

    • Use case

      • When all the parameters are explicit passed and the method do not need fields from objects.
      • When only static fields needs to be accessed.
  4. Factory Methods

    TO BE ADDED.

  5. The main Method

    • The reason main is static is that it doesn't have to create(access) a object to be called. (When a program start, there is no objects.)

    • Every class has a main method where you could add some domo codes.

      Run with java XXX,XXX is the class name.

      And if the class belongs to a larger application, the demo code won't be executed. (looks like Python's __main__)

  6. An Example

    ```java /* * This program demonstrates static methods. * @version 1.02 2008-04-10 * @author Cay Horstmann / public class StaticTest { public static void main(String[] args) { // fill the staff array with three Employee objects var staff = new Employee[3];

        staff[0] = new Employee("Tom", 40000);
        staff[1] = new Employee("Dick", 60000);
        staff[2] = new Employee("Harry", 65000);
    
        // print out information about all Employee objects
        for (Employee e : staff) {
            System.out.println("name=" + e.getName() + ",id=" + e.getId()
                + ",salary=" + e.getSalary());
        }
    
        int n = Employee.getNextId(); // calls static method
        System.out.println("Next available id=" + n);
    }
    

    }

    public class Employee { private static int nextId = 1;

    private String name;
    private double salary;
    private int id;
    
    public Employee(String n, double s) {
        name = n;
        salary = s;
        id = advanceId();
    }
    
    public String getName() {
        return name;
    }
    
    public double getSalary() {
        return salary;
    }
    
    public int getId() {
        return id;
    }
    
    public static int advanceId() {
        int r = nextId; // obtain next available id
        nextId++;
        return r;
    }
    
    public static void main(String[] args) // unit test
    {
        var e = new Employee("Harry", 50000);
    
        System.out.println(e.getName() + " " + e.getSalary());
    }
    

    } ```

Thoughts? Leave a comment