Posts

Showing posts from November, 2011

Where to declare Constants in Java

Its been an topic of debate where should constants be declared. Let look at approaches :- Declared in an Interface. Declared in a Class. Enums Going through google, i found number of explanation for both of these. Each have their pros and cons. I'll try to summarise and share my thoughts on it. Lets start with interface . In Java, Interfaces are used as abstract type, that contain method signatures, constants and nested types as  according to Oracle . We can use interfaces to defined a contract or for communication  as explained in my previous article . If we define constants here, we can have the following consequences:- We cannot stop a class to not implement an interface.So a Global constant interface can be used for subtype which is not advisable. We cannot give define constants depend on certain state condition. All the constants would stay in memory all the time. Although, we can define constants in interfaces, we have the above constraints. Lets look how we ov