• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class Vs Interface  RSS feed

 
vishwa venkat
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
which is best place to define some public final constants? what are things to consider?

Thanks,
-Visu
 
Ajith George
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use either an interface or class. But it depends on which you must go for. If you are using interface the advantage is that you can implement this interface on where ever you need to use those values. This method saves memory coz no object is being created here.

So if you need nice performance go for interface..................... :roll:
 
Michael Duffy
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ajith George:
You can use either an interface or class. But it depends on which you must go for. If you are using interface the advantage is that you can implement this interface on where ever you need to use those values. This method saves memory coz no object is being created here.

So if you need nice performance go for interface..................... :roll:


Since public static final constants are always associated with a class, not an instance, there's no memory savings to be had by putting constants in an interface.

I think constants should be defined with the class where they are pertinent. Follow the example of Java itself. There's no single interface or class where java.lang.Math.PI and java.util.Calendar.DECEMBER are defined. They're declared with the rest of the class that makes sense. you should do the same.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While you should avoid the "constant interface anti-pattern" there are times when constants are logically part of the interface, for example, for enumerated valued pass to or returned from methods in the interface. Here's a demo using constants and enums. Either way, it makes sense to include them in the interface. (Hmmm.... maybe they should have been defined in the IceCreamCone interface, but you get the idea...)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!