Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static import in Java [closed]

Tags:

java

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?

like image 956
Puneet Avatar asked Jan 31 '26 18:01

Puneet


2 Answers

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;
}
like image 116
Andy McSherry Avatar answered Feb 02 '26 08:02

Andy McSherry


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.

like image 36
Nandkumar Tekale Avatar answered Feb 02 '26 09:02

Nandkumar Tekale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!