Why are interface variables static and final by default in Java?
From the Java interface design FAQ by Philip Shaw:
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
source
public: for the accessibility across all the classes, just like the methods present in the interface
static: as interface cannot have an object, the interfaceName.variableName can be used to reference it or directly the variableName in the class implementing it.
final: to make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur in the current value of the var, which is why only one time initialization is permitted.
Also all these modifiers are implicit for an interface, you dont really need to specify any of them.
Since interface doesn't have a direct object, the only way to access them is by using a class/interface and hence that is why if interface variable exists, it should be static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one value and any classes that implements it can change it and hence it will be all mess.
Hence if at all there is an interface variable, it will be implicitly static, final and obviously public!!!
(This is not a philosophical answer but more of a practical one). The requirement for static modifier is obvious which has been answered by others. Basically, since the interfaces cannot be instantiated, the only way to access its fields are to make them a class field -- static.
The reason behind the interface fields automatically becoming final (constant) is to prevent different implementations accidentally changing the value of interface variable which can inadvertently affect the behavior of the other implementations. Imagine the scenario below where an interface property did not explicitly become final by Java:
public interface Actionable {
public static boolean isActionable = false;
public void performAction();
}
public NuclearAction implements Actionable {
public void performAction() {
// Code that depends on isActionable variable
if (isActionable) {
// Launch nuclear weapon!!!
}
}
}
Now, just think what would happen if another class that implements Actionable alters the state of the interface variable:
public CleanAction implements Actionable {
public void performAction() {
// Code that can alter isActionable state since it is not constant
isActionable = true;
}
}
If these classes are loaded within a single JVM by a classloader, then the behavior of NuclearAction can be affected by another class, CleanAction, when its performAction() is invoke after CleanAction's is executed (in the same thread or otherwise), which in this case can be disastrous (semantically that is).
Since we do not know how each implementation of an interface is going to use these variables, they must implicitly be final.
Because anything else is part of the implementation, and interfaces cannot contain any implementation.
public interface A{
int x=65;
}
public interface B{
int x=66;
}
public class D implements A,B {
public static void main(String[] a){
System.out.println(x); // which x?
}
}
Here is the solution.
System.out.println(A.x); // done
I think it is the one reason why interface variable are static.
Don't declare variables inside Interface.
because:
Static : as we can't have objects of interfaces so we should avoid using Object level member variables and should use class level variables i.e. static.
Final : so that we should not have ambiguous values for the variables(Diamond problem - Multiple Inheritance).
And as per the documentation interface is a contract and not an implementation.
reference: Abhishek Jain's answer on quora
static - because Interface cannot have any instance. and final - because we do not need to change it.
Interface : System requirement service.
In interface, variable are by default assign by public,static,final access modifier.
Because :
public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.
static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of interface_filename.variable_name
final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.
Java does not allow abstract variables and/or constructor definitions in interfaces. Solution: Simply hang an abstract class between your interface and your implementation which only extends the abstract class like so:
public interface IMyClass {
void methodA();
String methodB();
Integer methodC();
}
public abstract class myAbstractClass implements IMyClass {
protected String varA, varB;
//Constructor
myAbstractClass(String varA, String varB) {
this.varA = varA;
this.varB = VarB;
}
//Implement (some) interface methods here or leave them for the concrete class
protected void methodA() {
//Do something
}
//Add additional methods here which must be implemented in the concrete class
protected abstract Long methodD();
//Write some completely new methods which can be used by all subclasses
protected Float methodE() {
return 42.0;
}
}
public class myConcreteClass extends myAbstractClass {
//Constructor must now be implemented!
myClass(String varA, String varB) {
super(varA, varB);
}
//All non-private variables from the abstract class are available here
//All methods not implemented in the abstract class must be implemented here
}
You can also use an abstract class without any interface if you are SURE that you don't want to implement it along with other interfaces later. Please note that you can't create an instance of an abstract class you MUST extend it first.
(The "protected" keyword means that only extended classes can access these methods and variables.)
spyro
An Interface is contract between two parties that is invariant, carved in the stone, hence final. See Design by Contract.
In Java, interface doesn't allow you to declare any instance variables. Using a variable declared in an interface as an instance variable will return a compile time error.
You can declare a constant variable, using static final which is different from an instance variable.
Interface can be implemented by any classes and what if that value got changed by one of there implementing class then there will be mislead for other implementing classes. Interface is basically a reference to combine two corelated but different entity.so for that reason the declaring variable inside the interface will implicitly be final and also static because interface can not be instantiate.
Think of a web application where you have interface defined and other classes implement it. As you cannot create an instance of interface to access the variables you need to have a static keyword. Since its static any change in the value will reflect to other instances which has implemented it. So in order to prevent it we define them as final.
Just tried in Eclipse, the variable in interface is default to be final, so you can't change it. Compared with parent class, the variables are definitely changeable. Why? From my point, variable in class is an attribute which will be inherited by children, and children can change it according to their actual need. On the contrary, interface only define behavior, not attribute. The only reason to put in variables in interface is to use them as consts which related to that interface. Though, this is not a good practice according to following excerpt:
"Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data. As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class."
I also tried either put static or not makes no difference at all. The code is as below:
public interface Addable {
static int count = 6;
public int add(int i);
}
public class Impl implements Addable {
#Override
public int add(int i) {
return i+count;
}
}
public class Test {
public static void main(String... args) {
Impl impl = new Impl();
System.out.println(impl.add(4));
}
}
I feel like all these answers missed the point of the OP's question.
The OP did not ask for confirmation of their statement, they wanted to know WHY their statement is the standard.
Answering the question requires a little bit of information.
First, lets talk about inheretence.
Lets assume there is a class called A with an instance variable named x.
When you create a class A, it inhereits all the properties of the Object class. Without your knowledge when you instantiate A, you are instantiating an Object object as well, and A points to it as it's parent.
Now lets say you make a class B that inherits from A.
When you create a class B, you are also creating a class A and a Object.
B has access to the variable x. that means that B.x is really just the same thing as B.A.x and Java just hides the magic of grabbing A for you.
Not lets talk about interfaces...
An interface is NOT inheretence. If B were to implmement the interface Comparable, B is not making a Comparable instance and calling it a parent. Instead, B is promising to have the things that Comparable has.
Not lets talk a little bit of theory here... An interface is a set of functions you can use to interact with something. It is not the thing itself. For example, you interface with your friends by talking to them, sharing food with them, dancing with them, being near them. You don't inheret from them though - you do not have a copy of them.
Interfaces are similar. There is only one interface and all the objects associate with it. Since the interface exists only one time as a Class (as opposed to an instance of itself) it is not possible for each object that implements the interface to have their own copy of the interface. That means there is only one instance of each variable. That means the variables are shared by all the classes that use the interface (a.k.a. static).
As for why we make them public...
Private would be useless. The functions are abstract and cannot have any code inside them to use teh private variable. It will always be unused. If the variable is marked as protected, then only an inheritor of the class will be able to use the variables. I don't think you can inhereit from interfaces. Public is the only viable option then.
The only design decision left is the 'final'. It is possible that you intend to change the shared variable between multiple instances of a class. (E.G. Maybe you have 5 players playing Monopoly and you want one board to exist so you have all the players meet the interface and a single shared Board - it might be that you want to actually make the board change based on the player functions...) [I recommend against this design]
For multithreaded applicatiosn though, if you don't make the variable static you will have a difficult time later, but I won't stop you. Do it and learn why that hurts <3
So there you go. final public static variables
Related
Why are interface variables static and final by default in Java?
From the Java interface design FAQ by Philip Shaw:
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
source
public: for the accessibility across all the classes, just like the methods present in the interface
static: as interface cannot have an object, the interfaceName.variableName can be used to reference it or directly the variableName in the class implementing it.
final: to make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur in the current value of the var, which is why only one time initialization is permitted.
Also all these modifiers are implicit for an interface, you dont really need to specify any of them.
Since interface doesn't have a direct object, the only way to access them is by using a class/interface and hence that is why if interface variable exists, it should be static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one value and any classes that implements it can change it and hence it will be all mess.
Hence if at all there is an interface variable, it will be implicitly static, final and obviously public!!!
(This is not a philosophical answer but more of a practical one). The requirement for static modifier is obvious which has been answered by others. Basically, since the interfaces cannot be instantiated, the only way to access its fields are to make them a class field -- static.
The reason behind the interface fields automatically becoming final (constant) is to prevent different implementations accidentally changing the value of interface variable which can inadvertently affect the behavior of the other implementations. Imagine the scenario below where an interface property did not explicitly become final by Java:
public interface Actionable {
public static boolean isActionable = false;
public void performAction();
}
public NuclearAction implements Actionable {
public void performAction() {
// Code that depends on isActionable variable
if (isActionable) {
// Launch nuclear weapon!!!
}
}
}
Now, just think what would happen if another class that implements Actionable alters the state of the interface variable:
public CleanAction implements Actionable {
public void performAction() {
// Code that can alter isActionable state since it is not constant
isActionable = true;
}
}
If these classes are loaded within a single JVM by a classloader, then the behavior of NuclearAction can be affected by another class, CleanAction, when its performAction() is invoke after CleanAction's is executed (in the same thread or otherwise), which in this case can be disastrous (semantically that is).
Since we do not know how each implementation of an interface is going to use these variables, they must implicitly be final.
Because anything else is part of the implementation, and interfaces cannot contain any implementation.
public interface A{
int x=65;
}
public interface B{
int x=66;
}
public class D implements A,B {
public static void main(String[] a){
System.out.println(x); // which x?
}
}
Here is the solution.
System.out.println(A.x); // done
I think it is the one reason why interface variable are static.
Don't declare variables inside Interface.
because:
Static : as we can't have objects of interfaces so we should avoid using Object level member variables and should use class level variables i.e. static.
Final : so that we should not have ambiguous values for the variables(Diamond problem - Multiple Inheritance).
And as per the documentation interface is a contract and not an implementation.
reference: Abhishek Jain's answer on quora
static - because Interface cannot have any instance. and final - because we do not need to change it.
Interface : System requirement service.
In interface, variable are by default assign by public,static,final access modifier.
Because :
public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.
static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of interface_filename.variable_name
final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.
Java does not allow abstract variables and/or constructor definitions in interfaces. Solution: Simply hang an abstract class between your interface and your implementation which only extends the abstract class like so:
public interface IMyClass {
void methodA();
String methodB();
Integer methodC();
}
public abstract class myAbstractClass implements IMyClass {
protected String varA, varB;
//Constructor
myAbstractClass(String varA, String varB) {
this.varA = varA;
this.varB = VarB;
}
//Implement (some) interface methods here or leave them for the concrete class
protected void methodA() {
//Do something
}
//Add additional methods here which must be implemented in the concrete class
protected abstract Long methodD();
//Write some completely new methods which can be used by all subclasses
protected Float methodE() {
return 42.0;
}
}
public class myConcreteClass extends myAbstractClass {
//Constructor must now be implemented!
myClass(String varA, String varB) {
super(varA, varB);
}
//All non-private variables from the abstract class are available here
//All methods not implemented in the abstract class must be implemented here
}
You can also use an abstract class without any interface if you are SURE that you don't want to implement it along with other interfaces later. Please note that you can't create an instance of an abstract class you MUST extend it first.
(The "protected" keyword means that only extended classes can access these methods and variables.)
spyro
An Interface is contract between two parties that is invariant, carved in the stone, hence final. See Design by Contract.
In Java, interface doesn't allow you to declare any instance variables. Using a variable declared in an interface as an instance variable will return a compile time error.
You can declare a constant variable, using static final which is different from an instance variable.
Interface can be implemented by any classes and what if that value got changed by one of there implementing class then there will be mislead for other implementing classes. Interface is basically a reference to combine two corelated but different entity.so for that reason the declaring variable inside the interface will implicitly be final and also static because interface can not be instantiate.
Think of a web application where you have interface defined and other classes implement it. As you cannot create an instance of interface to access the variables you need to have a static keyword. Since its static any change in the value will reflect to other instances which has implemented it. So in order to prevent it we define them as final.
Just tried in Eclipse, the variable in interface is default to be final, so you can't change it. Compared with parent class, the variables are definitely changeable. Why? From my point, variable in class is an attribute which will be inherited by children, and children can change it according to their actual need. On the contrary, interface only define behavior, not attribute. The only reason to put in variables in interface is to use them as consts which related to that interface. Though, this is not a good practice according to following excerpt:
"Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data. As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class."
I also tried either put static or not makes no difference at all. The code is as below:
public interface Addable {
static int count = 6;
public int add(int i);
}
public class Impl implements Addable {
#Override
public int add(int i) {
return i+count;
}
}
public class Test {
public static void main(String... args) {
Impl impl = new Impl();
System.out.println(impl.add(4));
}
}
I feel like all these answers missed the point of the OP's question.
The OP did not ask for confirmation of their statement, they wanted to know WHY their statement is the standard.
Answering the question requires a little bit of information.
First, lets talk about inheretence.
Lets assume there is a class called A with an instance variable named x.
When you create a class A, it inhereits all the properties of the Object class. Without your knowledge when you instantiate A, you are instantiating an Object object as well, and A points to it as it's parent.
Now lets say you make a class B that inherits from A.
When you create a class B, you are also creating a class A and a Object.
B has access to the variable x. that means that B.x is really just the same thing as B.A.x and Java just hides the magic of grabbing A for you.
Not lets talk about interfaces...
An interface is NOT inheretence. If B were to implmement the interface Comparable, B is not making a Comparable instance and calling it a parent. Instead, B is promising to have the things that Comparable has.
Not lets talk a little bit of theory here... An interface is a set of functions you can use to interact with something. It is not the thing itself. For example, you interface with your friends by talking to them, sharing food with them, dancing with them, being near them. You don't inheret from them though - you do not have a copy of them.
Interfaces are similar. There is only one interface and all the objects associate with it. Since the interface exists only one time as a Class (as opposed to an instance of itself) it is not possible for each object that implements the interface to have their own copy of the interface. That means there is only one instance of each variable. That means the variables are shared by all the classes that use the interface (a.k.a. static).
As for why we make them public...
Private would be useless. The functions are abstract and cannot have any code inside them to use teh private variable. It will always be unused. If the variable is marked as protected, then only an inheritor of the class will be able to use the variables. I don't think you can inhereit from interfaces. Public is the only viable option then.
The only design decision left is the 'final'. It is possible that you intend to change the shared variable between multiple instances of a class. (E.G. Maybe you have 5 players playing Monopoly and you want one board to exist so you have all the players meet the interface and a single shared Board - it might be that you want to actually make the board change based on the player functions...) [I recommend against this design]
For multithreaded applicatiosn though, if you don't make the variable static you will have a difficult time later, but I won't stop you. Do it and learn why that hurts <3
So there you go. final public static variables
I was going through a part of a code which was something like this
// compare points according to their polar radius
public static final Comparator<Point2D> R_ORDER = new ROrder();
.
.
.
private static class ROrder implements Comparator<Point2D> {
public int compare(Point2D p, Point2D q) {
double delta = (p.x*p.x + p.y*p.y) - (q.x*q.x + q.y*q.y);
if (delta < 0) return -1;
if (delta > 0) return +1;
return 0;
}
}
Why do we have such public methods inside private static classes. What harm would it do if i made ROrder
Non-Static
Public
ROrder Non-Static
By making it non-static you will need the instance of the container class to create the instance of ROder, which maybe due to the design of the class would not make logic. You should keep class non-static only when you really need the instance of outer class to get the instance of inner class.
ROrder Public
Again because they wanted to restrict the use of ROrder outside the context of this class. They did not want any client code or other code to freely create instances of ROrder, as they would not be of any use.
Why do we have such public methods inside private static classes.
In this case because you are implementing an interface Comparator and you will pass this comparator for other uses, such as sorting and you would want the Collections class to have the visibility of compare method, so the method has to be public even if the class implementing the interface is private.
So this is just a logical way to enhance the readability and intent of use of the code.
Logical Use
This class wants the string to be in some format.
public class SomeClass{
private static class StringHelper{
//will do the task of parsing and validating that string object
}
}
Now in this case you would not want to keep StringHelper class public, as its use is too localized to be reused. So you would rather emphasize that by keeping it private. And there can be methods that are public if StringHelper implemented some interface.
UPDATE:
You should keep class non-static only when you really need the
instance of outer class to get the instance of inner class.
On that I think the answer can be too broad, but I would try to explain in short. By that what I mean was that if the inner class object shares some state of the outer object on which its processing is dependent, then you will need the object of outer class to share its state with the inner class object, but if the inner class instance is independent of the state of outer class, then it is safe to keep the inner class static.
This class implements Comparator and so must implement its methods. The implementation methods can't be static. Also, since interface methods are implicitly public, they must be declared public, regardless of the containing class's visibility. Try not doing so and it will fail to compile. This is certainly the reason it is declared public here -- it can't not be.
This is true regardless of whether the containing class is static or public. Here, it could be either of those things and the method inside would still have to be public and non-static.
Other methods that don't implement an interface could be private, and, logically probably should inside a private class as there would be no point in declaring it otherwise -- but it would be allowed by Java syntax.
All private members (fields, classes, whatever) are only visible inside the class. So, it doesn't matter what visibility you give a method of a private class - all methods will only be visible inside the containing class, because the class itself is private.
If the inner class implements an interface or extends a class, overridden methods may not have less visibility than the declaration in the super type, so that's one reason to have public methods in a private inner class.
However, although the syntax allows private classes to have public methods, it won't increase the visibility of those methods sufficiently to be visible outside the containing class. There are several examples in java of modifiers being legal but having no effect, such as inner interfaces being implicitly static (whether or not the static keyword is used).
This class is private because developer did not want to ROrder be instantiated in other place. But an instance can be accessed through the constant R_ORDER from other classes.
The method is public for two reason : first, compare is defined in the Comparator interface. Second, as R_ORDER is accessible from other classes, it is more than convenient to be able to call a method on this object. In this case, it is compare.
Finally, if the class was not static, it would keep a reference to the parent class, which is almost always not needed
I have 2 classes A and B.
class A implements Constants{
private int state;
}
class B implements Constants{
foo(){
//want to set state variable of class A like this
state = state1
}
}
interface Constants{
public final int state1;
public final int state2;
}
I don't want to have an instance of class A in class B. How should I do this?
If I have a function to set the variable in the interface, then both the classes must implement this function. That would be wrong right? Because then 2 definitions for the same function would conflict?
There is nothing called functions in java. They are methods.
You can have getters and setters in your classes for the properties to set and get them from external classes.
Your question is unclear.
If your B class extends the A class, then through the constructor of the B class, you can set the properties of the A class that is the super class.
Hope it helps!
Having an interface does not mean that the variable will be shared between the classes, it is more of a way to define classes that MUST override the functions in the interface. You can read the very basics on them here. To share a variable between two classes, you can either make the variable static and put it in another class that both your classes extend (in effect a global variable, which is bad practice and not thread safe), or have one of the classes have an instance of the other and call getters/setters.
EDIT: there is a similar question here that shows you what I mean about the static variable.
You generally want to avoid writing any method in a class that attempts to alter the internal state of another class. Whatever trick you come up with to accomplish such a thing, you are breaking the principle of encapsulation which is the whole reason for using classes in the first place.
If there is some state that you wish to have accessible from multiple classes, I would recommend breaking that state out into it's own class and have each of the two classes interact with it through getter/setter or utility methods.
I am just trying to understand why all fields defined in an Interface are implicitly static and final. The idea of keeping fields static makes sense to me as you can't have objects of an interface but why they are final (implicitly)?
Any one knows why Java designers went with making the fields in an interface static and final?
An interface is intended to specify an interaction contract, not implementation details. A developer should be able to use an implementation just by looking at the interface, and not have to look inside the class which implements it.
An interface does not allow you to create an instance of it, because you cannot specify constructors. So it cannot have instance state, although interface fields can define constants, which are implicitly static and final.
You cannot specify method bodies or initializer blocks in an interface, although since Java 8 you can specify default methods with bodies. This feature is intended to allow new methods to be added to existing interfaces without having to update all the implementations. But you still cannot execute such a method, without first creating an instance implementing the interface.
Aside: Note that you can implement an interface with an anonymous inner class:
interface Foo {
String bar();
}
class FooBar {
Foo anonymous = new Foo() {
public String bar() {
return "The Laundromat Café";
};
}
You have to provide the full implementation of the interface for the anonymous inner class to compile.
new Foo() is initializing the anonymous inner class with its default constructor.
Reason for being final
Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation. An interface is a pure specification without any implementation.
Reason for being static
If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
There are a couple of points glossed over here:
Just because fields in an interface are implicitly static final does not mean they must be compile-time constants, or even immutable. You can define e.g.
interface I {
String TOKEN = SomeOtherClass.heavyComputation();
JButton BAD_IDEA = new JButton("hello");
}
(Beware that doing this inside an annotation definition can confuse javac, relating to the fact that the above actually compiles to a static initializer.)
Also, the reason for this restriction is more stylistic than technical, and a lot of people would like to see it be relaxed.
The fields must be static because they can't be abstract (like methods can). Because they can't be abstract, the implementers will not be able to logically provide the different implementation of the fields.
The fields must be final, I think, because the fields may be accessed by many different implementers allows they to be changeable might be problematic (as synchronization). Also to avoid it to be re-implemented (hidden).
Just my thought.
I consider the requirement that the fields be final as unduly restrictive and a mistake by the Java language designers. There are times, e.g. tree handling, when you need to set constants in the implementation which are required to perform operations on an object of the interface type. Selecting a code path on the implementing class is a kludge. The workaround which I use is to define an interface function and implement it by returning a literal:
public interface iMine {
String __ImplementationConstant();
...
}
public class AClass implements iMine {
public String __ImplementationConstant(){
return "AClass value for the Implementation Constant";
}
...
}
public class BClass implements iMine {
public String __ImplementationConstant(){
return "BClass value for the Implementation Constant";
}
...
}
However, it would be simpler, clearer and less prone to aberrant implementation to use this syntax:
public interface iMine {
String __ImplementationConstant;
...
}
public class AClass implements iMine {
public static String __ImplementationConstant =
"AClass value for the Implementation Constant";
...
}
public class BClass implements iMine {
public static String __ImplementationConstant =
"BClass value for the Implementation Constant";
...
}
Specification, contracts... The machine instruction for field access uses object address plus field offset. Since classes can implement many interfaces, there is no way to make non-final interface field to have the same offset in all classes that extend this interface. Therefore different mechanism for field access must be implemented: two memory accesses (get field offset, get field value) instead of one plus maintaining kind of virtual field table (analog of virtual method table). Guess they just didn't want to complicate jvm for functionality that can be easily simulated via existing stuff (methods).
In scala we can have fields in interfaces, though internally they are implemented as I explained above (as methods).
static:
Anything (variable or method) that is static in Java can be invoked as Classname.variablename or Classname.methodname or directly. It is not compulsory to invoke it only by using object name.
In interface, objects cannot be declared and static makes it possible to invoke variables just through class name without the need of object name.
final:
It helps to maintain a constant value for a variable as it can't be overridden in its subclasses.
I have just found a static nested interface in our code-base.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).
Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification 8.5.1. Static Member Type Declarations
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:
public class Baz implements Foo.Bar {
...
}
In most ways, this isn't different from a static inner class.
Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.
class ConcreteA implements A {
:
}
class ConcreteB implements B {
:
}
class ConcreteC implements C {
:
}
class Zoo implements A, C {
:
}
class DoSomethingAlready {
interface AC extends A, C { }
private final AC ac;
DoSomethingAlready(AC ac) {
this.ac = ac;
}
}
To answer your question very directly, look at Map.Entry.
Map.Entry
also this may be useful
Static Nested Inerfaces blog Entry
Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)
If you will change class Foo into interface Foo the "public" keyword in the above example will be also redundant as well because
interface defined inside another interface will implicitly public
static.
In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.
So far as I can see, the only difference in making an
interface non-static is that it can now include non-static inner
classes; so the change would not render invalid any existing Java
programs.
For example, he proposed a solution to the Expression Problem, which is the mismatch between expression as "how much can your language express" on the one hand and expression as "the terms you are trying to represent in your language" on the other hand.
An example of the difference between static and non-static nested interfaces can be seen in his sample code:
// This code does NOT compile
class LangF<This extends LangF<This>> {
interface Visitor<R> {
public R forNum(int n);
}
interface Exp {
// since Exp is non-static, it can refer to the type bound to This
public <R> R visit(This.Visitor<R> v);
}
}
His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.
In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:
class Bob
{
void FuncA ()
{
Foo.Bar foobar;
}
}
Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.
A description of class types in Java.
Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.
The perfect example of the usefullnes of "static" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.
Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.
Static methods are good for one-time returns and quick calculations or easy obtained data.