Note that there are some explanatory texts on larger screens.

plurals
  1. PORegarding alternative to interfaces and acessing with static imorts
    primarykey
    data
    text
    <p>I was going through a research in which I dont want to store the constants in the interface itself, so I was looking for alternatives like enums but another approach I have found is that ....t instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data. and we can also take the advantage of static import in that case</p> <pre><code>Public final class KittenConstants { private KittenConstants() {} public static final String KITTEN_SOUND = "meow"; public static final double KITTEN_CUTENESS_FACTOR = 1; } </code></pre> <p>two independent things. 1: use static imports instead of abusing inheritance. 2: If you must have a constants repository, make it a final class instead of an interface . Please advise is this approach is correct..!!</p> <p>To avoid some pitfalls of the constant interface (because you can't prevent people from implementing it), a proper class with a private constructor should be preferred (example borrowed from Wikipedia):</p> <pre><code>public final class Constants { private Constants() { // restrict instantiation } public static final double PI = 3.14159; public static final double PLANCK_CONSTANT = 6.62606896e-34; } </code></pre> <p>And to access the constants without having to fully qualify them (i.e. without having to prefix them with the class name), use a static import (since Java 5):</p> <pre><code>import static Constants.PLANCK_CONSTANT; import static Constants.PI; public class Calculations { public double getReducedPlanckConstant() { return PLANCK_CONSTANT / (2 * PI); } } </code></pre> <p>Please show how we can do same ting with enum also..!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload