1

Possible Duplicate:
What is the use of interface constants?

I am creating a calculator program inside Eclipse EE and wanted to know if it would be correct to write interfaces within the project and also when would it ever be necessary or fitting to declare variable within an interface in Java?

Also, I wanted to know if I should create an abstract class within my calculator program My calculator program follows the basic model-view-controller pattern.

Community
  • 1
  • 1
Chris Olszewski
  • 153
  • 2
  • 8
  • 5
    A variable within an interface will be a static constant by default. – assylias Jan 24 '13 at 16:09
  • 2
    This question will have different answers when Java 8 is released. – Perception Jan 24 '13 at 16:10
  • @Perception I don't think it will change the semantics of interface variables, will it? – assylias Jan 24 '13 at 16:11
  • 1
    @assylias - at the last state of interface default methods there was discussion on the need for non-static interface variables. But that spec is still in flux so it might not make it into final. – Perception Jan 24 '13 at 16:13
  • 1
    The decision whether to use interfaces and abstract classes is complex and depends on the design of the application being written. Your description of the calculator is insufficient to make that determination. – NickJ Jan 24 '13 at 16:13
  • @Perception you can add virtual extensions to interfaces in Java 8, but you will cannot have anything but `public static final` fields. – Peter Lawrey Jan 24 '13 at 18:11

1 Answers1

4

All variables in an interface are static constants. Although you are not writing it explicitly, they are still public, static and final.

This in an interface

String msg = "Please enter value : "

is the same as

public final static String msg = "Please enter value : "

Generally all the constants are kept in a Interface and used all over the project by interface_name.variable name.

Seitaridis
  • 4,459
  • 9
  • 53
  • 85
Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40
  • 2
    even "public static final String" :D – Grim Jan 24 '13 at 16:13
  • 1
    The above question and the replies are fine. But, using an interface to declare constants is not recommended. Take a look at http://stackoverflow.com/questions/66066/what-is-the-best-way-to-implement-constants-in-java – techuser soma Jan 24 '13 at 16:48
  • @javausersoma seeing at the link, first answer is saying that don't use its "OWN" class or interface to define the constants. What ever he gave example that though object is constant, its state not. For this u can create immutable objects by making members and private and not providing setter methods instead of that create a parameterized constructor. – Vallabh Patade Jan 24 '13 at 16:54