Java static story

Introduction

This article is the 18th day article of MicroAd Advent Calendar 2017 .

Is it something that I don't usually think about? If I don't talk about it now, I won't talk about it in the future, so I'm going to talk about static in java.

goal

Only static but static, While writing a simple quiz, let's easily organize static things in java once again.

static field

In the first place, static means "static". ~~ ~~ By saying "not dynamic", the field is only one in the class, no matter how many instances you create. Add static to the fields that you want to be shared resources, information that will continue to be shared between multiple instances. Call it with `class name.field name`. You can access the same thing by creating an instance and calling it.

Declaring with final static when defining a constant prevents the same value from being replicated to the instance every time you new, which helps save memory.

public final static String KEY = "happy-toilet";

It is a fixed value of Happy Toilet that can be called anywhere.

static method (class method)

Static methods themselves belong to a class, not an instance of the class. Calls can be made directly with `class name.method name`, and for functional interface method references, with `class name :: method name`. Along with static fields, they are called static members. General methods without static are called non-static methods and instance methods.

The following is the difference between static method and instance method calls in functional interface method references since java8.

MethodReference.java


public class MethodReference {

  public static void main(String[] args) {
    //static method
    wakeUp(MethodReference::printWakeUp);

    System.out.print(" and ");

    //Instance method
    MethodReference mr = new MethodReference();
    mr.goToilet(mr::printGoToilet);
  }

  interface Human {
    void doSomething();
  }

  static void wakeUp(Human human) {
    human.doSomething();
  }

  static void printWakeUp() {
    String wakeUp = "wake up";
    System.out.print(wakeUp);
  }

  void goToilet(Human human) {
    human.doSomething();
  }

  void printGoToilet() {
    String toilet = "happy toilet";
    System.out.print(toilet);
  }
}

The result is wake up and happy toilet </ font>.

Cannot be overridden

public class StaticPractice {

  public static void main(String[] args) {

    Human developer = new Developer();

    System.out.println(developer.getMorning());

  }
}

class Human {
  static String morning = "Happy Toilet";

  static String getMorning() {
    return morning;
  }
}

class Developer extends Human {
  static String morning = "Happy Coding";

  static String getMorning() {
    return morning;
  }
}

Of course the result is Happy Toilet </ font>.

If you change it to Developer developer = new Developer ();, you can do Happy Coding for the time being.

However, here I create an instance just to represent cannot be overridden and call from that instance, but in the first place the static method is

 Human.getMorning();
 Developer.getMorning();

And it is desirable to refer to it from the class itself without going through the instance.

In fact, if you just transfer the above code to IntelliJ

alert.png

Noted as a static methodnot referenced by theclass itself.

(Special thanks to @kawamnv)

public static void main(String [] args) This is because when the main method is called, the instance does not yet exist in memory, so the main method must be executed even if the class containing it is not instantiated.

static class (static inner class)

There are three types of classes, inner classes, member classes, local classes, and anonymous classes. A static member class is one of the member classes, and the declaration location is in the class block (the same position as the field and method). However, strictly speaking, a static member class is hard to call an inner class, and it is more correct to describe it as a completely different class.

If you call the class that encloses the inner class the outer class, It has a relatively weak relationship with the outer class and its instances, and can also access the static members of the outer class.

Like other static things, it is used with `external class name.member class name`.

Outer.java


class Outer { //External class

  //Member class ➀ static class
  static class StaticInner {
    private Integer in;

    public Integer getIn() {
      return in;
    }

    public void setIn(Integer in) {
      this.in = in;
    }
  }

  //Member class ➁ Strict member class
  class Inner {
    private String str;

    public String getStr() {
      return str;
    }

    public void setStr(String str) {
      this.str = str;
    }
  }
}

Calls in irrelevant classes and main methods are:

Execute.java


class Execute {
  public static void main(String[] args) {
    //static class
    Outer.StaticInner staticInner = new Outer.StaticInner();

    //Strict member class
    Outer outer = new Outer();
    Outer.Inner inner = outer.new Inner();
  }
}

As I've included in the example above, a strict member class has strong ties to the individual instances created by the outer class, so you can't do a new without an instance of the outer class. Since it is not a static thing, non-static members are also allowed access.

static initializer

static {
  //processing
}

A static initializer is a block that is executed only once when a class is loaded (a .class file is loaded). Describe the process you want to call and execute before instantiating a class or before the main method. Of course, you can only describe static things.

Is there any use for it? I thought,

public final static String VALUE;

static {
  VALUE = makeValue();
} 

/**
 *Dynamically generate values under certain conditions
 * @return value generated value
 */
private static String makeValue() {
  // omit
}

The other day, I was able to try this kind of usage by accident. I think it was just right because the purpose was to "create a new value only once at the beginning, earlier than instantiation" and reuse it.

Constructor and static initializer

class Something {

  void printA() {
    System.out.print("t");
  }

  void printB() {
    System.out.print("e");
  }

  Something () {
    System.out.print("l");
    printB();
  }

  static {
    System.out.print("i");
  }
}

class StaticTest {
  static {
    System.out.print("T");
  }

  public static void main(String [] args) {
    System.out.print("o");
    new Something().printA();
  }
}

The result is Toilet </ font>. You can see that the static initializer is called earlier than the constructor that is finally called by new (instantiation).

static import declaration

Introduced since java5.

The following is the source used when creating the constraint annotation of previous post .

CustomSize.java


import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = {CustomSizeValidator.class})
public @interface CustomSize {
  // omit
}

In fact, ElementType and `` `RetentionPolicy``` are enums with long package names, so you can write them neatly as above.

If it is a static member of an external class, it can be used even if it is not an enum.

import static java.lang.System.*;
import static java.lang.Math.*;

The end

It is very important to reconfirm the basics of grammar as much as the first toilet in the morning.

that's all

Recommended Posts