javainheritancestatic-import

accessing static import of mother class in children class


We have a helper class that we often include via static import to be able to concisely access its static methods and fields.

We have an abstract class whose children could benefit from this helper. I was hoping to do the static import of the helper in the abstract class so that every sub-class can benefit from it, but it seems that Eclipse doesn't let me (import is deleted every time I save). Is it an Eclipse configuration problem? Or is it that the scope of the static import is limited to the class itself (and not its children).

Is there any other way to make the elements in the helper accessible to all the children classes without having to modify them each individually?

The helper:

public class FormatHelper {
    
    public static final NL="\r\n";

    public static String bold(String val) {
        return "*" + val + "*";
    }
   
    public static String underline(String val) {
        return "+" + val + "+";
    }
}

Normal use of this helper:

import static org.whatever.FormatHelper.NL
import static org.whatever.FormatHelper.bold
    
public class MyBusinessClass{
  
    public String doSomething(){
        return bold("much wow")+NL;  
    }
}

Now, I have an abstract class with around 20 subclasses, each of them needing to access bold/underline and some other static methods of FormatHelper.

I'd prefer not to have to write FormatHelper.NL every time, hence my wish to work with static imports.

I'd also prefer to have those elements in the subclasses scope from the get go. As, when creating new sub classes, I'd like to have a direct access to those methods, without having to think to add a static import.


Solution

  • Another way you could specify the format helper code is in an interface. You would need to change the static methods to default methods to allow the methods to be accessible in other classes without ClassName. prefix:

    public interface FormatHelper {
        public static final String NL= System.lineSeparator() ; // or "\r\n" if targetting Windows from non-Windows
    
        public default String bold(String val) {
            return "*" + val + "*";
        }
    
        public default String underline(String val) {
            return "+" + val + "+";
        }
    }
    

    Then the helper code definitions can be accessed from any implementing classes (abstract or otherwise):

    import xyz.FormatHelper;
    
    public class MyBusinessClass implements FormatHelper {
        public String doSomething(){
            return bold("much wow")+NL;
        }
    }
    

    Any class derived from MyBusinessClass would be able to access the same methods and fields without further imports, and without "FormatHelper." prefix.

    NOTE: this mechanism would not work within static methods of the calling classes, which may be a significant problem.