• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interface Constant or class based ?  RSS feed

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Lester Burnham
Rancher
Posts: 1337
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
interface test
{
public static final int a=10;
}

class test{

public static final int ;...

}
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!