Extending a non-intuitive class in java

I read "Effective Java" by Joshua Bloch and removed the "Anti-pattern" with a persistent interface from our application. The trick is to use the Non-instantiable util class, whose constructor is private, and define all the constants as "public static final"

I need to extend this constant util class. I can only do this when changing the constructor to protected.

Can anyone suggest a better way.

public class Constants {
    private Constants () {} // Prevent instantiation
    public static final String MyString = "MyString";
}

public class MyConstants extends Constants {
    private MyConstants () {} // Compiler error : Implicit super constructor Constants() is not visible.
    public static final String MySecondString = "MySecondString";
}
+5
source share
6 answers

Normally you should not distribute these constant classes. Could you provide us with a more concrete example of what you are trying to do?

, , , .

, ? , , ?

+7

:

public abstract class Constants {
    // ...constants...
    public Constants () {
        throw new UnsupportedOperationException();  // prevent instantiation
    }
}

, , , () . , java.util.Collections , Collections2 ( ) .

, "" "" . , , , "":

public class Base {
    protected Base() { }
}

// Somewhere else:
Base b = new Base() { };  // anonymous subclass
+3

.

.

+2

protected? .

( ), . static import, . .

+1

If the classes are in the same package and you want to prevent inheritance for classes other than the package, consider using default access:

public class Constants {
    Constants () {} // Prevent instantiation
    public static final String MyString = "MyString";
}
+1
source

I use the approach that Joshua Bloch recommends.

public class Constants {

    private Constants() {
        throw new AssertionError();
    }

    public static class Math {

        private Math() {
            throw new AssertionError();
        }

        public static final int COUNT = 12;
    }

    public static class Strings {

        private Strings() {
            throw new AssertionError();
        }

        public static final String LOREM = "Lorem";
    }

}

Class Constantsand nested classes

  • cannot be expanded
  • cannot be created

If I needed to group constants by type, I would just use nested classes. Remember that every nested class must throw AssertionError.

0
source

All Articles