[Solved] Why use “inner Class” instead of using “new” directly? [duplicate]


Your alternative suggestion

public static HashFunction crc32c() {
    return new Crc32cHashFunction()
}

would create a new Crc32cHashFunction instance each time crc32c() is called. If there is no specific need for a new instance to be returned by each call, it is more efficient to return the same instance in each call.

Using the static final variable

static final HashFunction CRC_32_C = new Crc32cHashFunction();

is one way to achieve a single instance.

As to why the HashFunction instance is a member of the nested class Crc32cHolder (as opposed to being a member of the outer class), the motivation is probably lazy evaluation – only at the first time the crc32c() method is called, the Crc32cHolder class would be initialized and the Crc32cHashFunction instance would be created. Thus, if that method is never called, the Crc32cHashFunction would never be created (assuming there is no other access to the Crc32cHolder class).

4

solved Why use “inner Class” instead of using “new” directly? [duplicate]