Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid repeated imports in Java: Inherit imports?

Is there a way to "inherit" imports?

Example:

Common enum:

public enum Constant{ ONE, TWO, THREE }

Base class using this enum:

public class Base {
    protected void register(Constant c, String t) {
      ...
    }
}

Sub class needing an import to use the enum constants convenient (without enum name):

import static Constant.*; // want to avoid this line!  
public Sub extends Base {
    public Sub() {
        register(TWO, "blabla"); // without import: Constant.TWO
    }
}

and another class with same import ...

import static Constant.*; // want to avoid this line!
public AnotherSub extends Base {
    ...
}

I could use classic static final constants but maybe there is a way to use a common enum with the same convenience.

like image 779
deamon Avatar asked Jan 11 '10 13:01

deamon


People also ask

Why is it better to avoid * in import statements in java?

Wildcard imports tell java compiler to search for class names in the given package. Hence, using wild card imports, the compile-time performance may lower a bit.

Are imports inherited java?

The import statements are only in the source code - they aren't in the bytecode and so inheriting a superclass's import statements is meaningless as you don't inherit source code - you inherit bytecode.

What is the difference between import and inheritance in java?

keywords import is used to import or call the files from outsourse to our java programe while keyword extends is used to inherit the class in the particular class.

Does order of imports matter java?

import statements should be sorted with the most fundamental packages first, and grouped with associated packages together and one blank line between groups. The import statement location is enforced by the Java language.


2 Answers

imports are just an aid to the compiler to find classes. They are active for a single source file and have no relation whatsoever to Java's OOP mechanisms.

So, no, you cannot “inherit” imports

like image 83
Joey Avatar answered Sep 17 '22 11:09

Joey


If you're using Eclipse, use "Organize Imports" (Ctrl+Shift+O) to let the IDE do the imports for you (or use code completion (Ctrl+Space)

like image 33
helpermethod Avatar answered Sep 16 '22 11:09

helpermethod