views:

191

answers:

3

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.

+3  A: 

No, you can't inherit an import. If you want to reference a type within a class file without using the fully-qualified name, you have to import it explicitly.

But in your example it would be easy enough to say

public Sub extends Base {
    public Sub() {
        register(Constant.TWO, "blabla"); // without import: Constant.TWO
    }
}
danben
+5  A: 

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

Joey
+3  A: 

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

Helper Method
Even better, set this up as a "Save Action" so Eclipse will organize them every time you save the file. This and formatting on Save helps save any brain cycles thinking about such things :)
matt b
Very good idea, totally forget about that ^^
Helper Method