This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Interface Constant or class based ? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Interface Constant or class based ?" Watch "Interface Constant or class based ?" New topic
Author

Interface Constant or class based ?

Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 361
Hi,

We can declare constant in java in Interface , as public static final

we can also do the same in class, so which one is the best.

Regards,
prabhat
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 8576

Prabhat Ranjan wrote:
we can also do the same in class, so which one is the best.


Best is relative and subjective.
Usually I go by the way how the java source code is written.
If you look at say SwingConstants, you will notice it is an interface.


[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
Lester Burnham
Rancher

Joined: Oct 14, 2008
Posts: 1337
In my opinion, using an interface just to keep constants is an abomination. Yes, Sun did it in the class libraries, but they also made some other questionable choices, so that shouldn't count for much.

But Java 5 gave us "static import" of a class, which accomplishes much the same, and is IMO a much cleaner way than to implement an interface.
Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 361
interface test
{
public static final int a=10;
}

class test{

public static final int ;...

}
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3065
    
    1

It's not an either or question. It depends on what the class or interface stands for.

Constants can belong to a certain interface as much as other constants belong to a certain class. Think of the place where these constants belong, and define them there.

Like Lester said, don't make an interface (or class!) specifically for the purpose of holding constants. Constants without context are meaningless.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Interface Constant or class based ?
 
Similar Threads
HFDP - Strategy Pattern
interface within a class
instantiating an interface
Retreival of values from interface to Jsp
Static methods in Java Interfaces?