Please can you give me a small demo in form a program I want to know that an interface can have constants that are static and final but then how can a class implementing that interface can use those constants while implementing that interface p, please provide a small example..!! Thanks
Like any static field, the constants are accessed with the class/interface name.variable name. The general principle being that when you're using the code (if you didn't have the javadoc or source) you can't tell the difference between a constant declared in an interface and a class.
Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
Why do we keep all the constants in an interface ...and why not in abstract class..what so special of keeping the constants in an interface itself...is there any design principle behind it..?
Personally, I always thought it seemed like a bad idea, and it led to the awful constants-only-interface antipattern. I don't think there's any design principle behind it. I think it's just for convenience and brevity. I've been working with Java for many years, and I don't think I've ever done it, or ever would.
Thanks for the explanation could you please explain once again in detail
(if you didn't have the javadoc or source) you can't tell the difference between a constant declared in an interface and a class.
Just saying that you access the constants in the Car interface the same way you'd access them if Car was a class. Both ways it's still Car.NUM_WHEELS.
I don't do constants in an interface normally either. It seems to me a bad idea to put implementation details such as data into a class that describes a behavior contract. In the example, what if I wanted to make a ThreeWheeledCar? It would still implement the behavior, drive() but the constants would get in the way. At least if you do it in an abstract class you have the option to use the abstract class when doing the implementation, or you could implement the interface directly and create your own constants.