What does mean by static import, like :
import static com.example.foo.Suggestion;
How to define such packages and what is advantages to use static import?
import static means that you can references a static value without using the class name.
For example, consider these three classes:
package com.example;
public class foo {
public static int Suggestion = 5;
}
import com.example.foo;
public class b {
// …
int var = foo.Suggestion;
}
import static com.example.foo.Suggestion;
public class c {
// …
int var = Suggestion;
}
Advantage of static import what I felt is over Constant Interface Pattern.
Generally we use interfaces for constant and it is implemented by all classes but if you are developing an API, it is something like you are exposing your implementation details. Above wiki link explains very well.
But use of static imports avoid this and provide very good solution to constant interface Anti-Pattern. Instead of constant interface pattern I would create a final class, create public static constants in that class, and do static import wherever Constants needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With