Link to home
Start Free TrialLog in
Avatar of krelman
krelman

asked on

constant class ?

public class  dddd()
{
   public static final String    YES            = "Y";
 
}

this class will include only constant .

Did the class need to be final , or abstract what is the best why to define a class that include only constant

thank
Avatar of tomboshell
tomboshell

This is how I would do it:


public  class MyConstant{
     private final static String YES ="Y";

     public static String getYes(){
          //quick access, only through here
          return YES;
     }
}

// and a testing class...
public class GrabConstant{
     public static void main(String[] args)
     {
          System.out.println(MyConstant.getYes());

     }
}
Avatar of CEHJ
If you are unlikely to  need to subclass dddd, then you should declare the class as final, as this has less overhead in the JVM and is therefore better performing.

public final class dddd
{
  public final String  YES = "Y";
}

No accessor methods are needed here as the members are declared final and there will be no subclasses that need to modify how the values are returned.
Avatar of krelman

ASKER

If all the constant are - final static , therefor nobady make from them a object , are this has less overhead in the JVM too.

Why don't you use interface?

public interface MyConstant
{
  public static final String YES = "Y";
}


If you are eager to use class, then I would do this:

public class MyConstant
{
 public final static MyConstant YES = new MyConstant("Y");

 private String name;
 private MyConstant(String name)
 {
   this.name = name;
 }

 public String toString()
 {
   return name;
 }
}

BTW, using that kind of class is much more type safe!
ASKER CERTIFIED SOLUTION
Avatar of yasser_helmy
yasser_helmy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If the class will never be subclassed then declare it as final as it will have performance benefits (as mentioned).  If it is possible that it will be subclassed then leave it as final.

To prevent instantiation use a private constructor (as mentioned by yasser_helmy).

IMHO it is preferable to use a class rather than an interface.  Declaring the constants in an interface does give the "nicety" of just using the constant name without a qualifying class (or interface), however, any class that implements the interface then exposes the constants as part of its interface (affecting the OO of the system).  Personally, I would rather have a cleaner object model than a (slight) time-saving development nicety.

--
flumpman