I have a class which is intended for immutable use, hence I would like to label all the fields final.
However the class is serialized and deserialized to send over the network. For this to work an empty constructor is required. This prevents me creating the final fields.
I'm sure this is a fairly common problem but I can't find a solution. How should I proceed?
A no-arg constructor is not required. The most derived non-serialisable class does need a no-arg constructor available to the least-most derived serialisable class.
If you need to mutate fields inside a readObject, then use a serial proxy through readResolve and writeReplace.
In the typical serialization case, it is not required that class have an empty constructor or non-final fields to be serializable.
Now, if you have to do your own serialization, or you need to subclass a class that doesn't implement Serializable, that is a different story.
So you need to provide some more details of how you are having a problem.
This issue is an open bug on the Java language. (Note that this only applies if you have to do the serialization manually, such as with readObject)
To echo what has been said, no-arg constructors are not a requirement if you are taking the route of implementing the java.io.Serializable interface. Take a look at the java.lang.Integer source code for example, a simple serializable/immutable class that has two constructors: one that takes an int, and one that takes a String. Source code: http://www.docjar.com/html/api/java/lang/Integer.java.html. Javadoc: http://java.sun.com/javase/6/docs/api/java/lang/Integer.html.
Also depending on the complexity of your class and what you are doing, you could consider implementing serialization via the java.io.Externalizable interface (although some consider it outdated, and it DOES require a no-arg constructor). Here's an overview on SO: What is the difference between Serializable and Externalizable in Java?, and here's the official Java tutorial: http://java.sun.com/docs/books/tutorial/javabeans/persistence/index.html.
For the record, since I had a similar issue:
I had a message "java.io.InvalidClassException: com.example.stuff.FooBar; com.example.stuff.FooBar; no valid constructor"
I thought it was because it was lacking a default constructor. But the above answers confirm it is not mandatory (but our app. uses an old serializer that indeed require a default constructor, so the case can arise).
Then I found a page stating:
If a class that is designed for inheritance is not serializable, it
may be impossible to write a serializable subclass. Specifically, it
will be impossible if the superclass does not provide an accessible
parameterless constructor.
Hence the message I got, I suppose. It appeared that the core issue was classical: I declared a class as serializable, but the superclass was not! I moved the Serializable interface up in the hierarchy, and all was well.
But the message was a bit misleading... :-)
A no-arg constructor is not required. Let's read the source code:
// java.io.ObjectStreamClass
private static Constructor<?> getSerializableConstructor(Class<?> cl) {
Class<?> initCl = cl;
while (Serializable.class.isAssignableFrom(initCl)) {
if ((initCl = initCl.getSuperclass()) == null) {
return null;
}
}
...
}
So, actually the no-arg constructor is required in the nearest not Serializable class in the type hierarchy.
It means the following class Domain can be serialized.
class Domain implements Serializable {
private final int a;
public Domain(int a) {
this.a = a;
}
}
But the class Son can't:
class Father{
private final int a;
public Father(int a) {
this.a = a;
}
}
class Son extends Father implements Serializable {
public Son(int a) {
super(a);
}
}
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 have a superclass like this which I expect alot of classes to inherit:
public abstract class Super {
protected Object myField; //Not used anywhere in this class
//a load more code here which does useful stuff
}
All these classes will need to use an instance of myField. However the superclass does not. Have I made a bad design decision somewhere?
Not necessarily. If all the subclasses need the same field for the same reason, then that's no different than providing any other common functionality in a base class. as your classes grow you may find that you add common functionality which uses this field (e.g. referencing it in an equals/hashCode method).
Now, if the field is of type Object and each sub-class shoves something completely different into it, i would consider that a code smell.
Well IMHO, a field should not be present in a class if it's not really used by that class. What it seems to me that you really want here is to have a base class that tells its subclasses "you should ALL have some way of keeping state for X but I (the base class) will not modify that X state, in which case you should make an abstract method in order to convey that message, something like this:
public abstract class Super {
protected abstract Object getMyField();
}
It's hard to say with such a vague description, but it would seem like you could do some generalization and push some common code up into your superclass. If your subclasses are doing something similar with the field then some commonality could be found (using template methods or strategies to handle subclass-specific differences), otherwise if every subclass is doing something different with it then what's the point of using a common field?
No, I don't think so. Abstract class serve that purpose (Have common functionality in base class and let subclass implement only specific required functionality).
So, if you don't use that field in class Super - why do you need it there?
Perhaps your super class would provide an interface to interact with this field in generic way, for example:
public abstract class Super<T> {
protected T myField;
public T getField() {
return myField;
}
}
public class Child extends Super<String> {
public Child( String label ) {
super.myField = label;
}
}
As stated in this tuturial
A protected field or method is accessible to the class itself, its subclasses, and classes in the same package.
This means that the protected fields have been designed precisely to have these characteristics.
Just on a lighter note The only thing common in your hirarchy is one field then you should get rid of abstract class and Create one Marker Interface.
I have a quite simple question:
I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...
This class should neither be instantiated, nor being extended. That made me write:
final abstract class MyClass {
static void myMethod() {
...
}
... // More private methods and fields...
}
(though I knew, it is forbidden).
I also know, that I can make this class solely final and override the standard constructor while making it private.
But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...
And I hate workarounds. So just for my own interest: Is there another, better way?
You can't get much simpler than using an enum with no instances.
public enum MyLib {;
public static void myHelperMethod() { }
}
This class is final, with explicitly no instances and a private constructor.
This is detected by the compiler rather than as a runtime error. (unlike throwing an exception)
Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"
public final class MyClass { //final not required but clearly states intention
//private default constructor ==> can't be instantiated
//side effect: class is final because it can't be subclassed:
//super() can't be called from subclasses
private MyClass() {
throw new AssertionError()
}
//...
public static void doSomething() {}
}
No, what you should do is create a private empty constructor that throws an exception in it's body. Java is an Object-Oriented language and a class that is never to be instantiated is itself a work-around! :)
final class MyLib{
private MyLib(){
throw new IllegalStateException( "Do not instantiate this class." );
}
// static methods go here
}
No, abstract classes are meant to be extended. Use private constructor, it is not a workaround - it is the way to do it!
Declare the constructor of the class to be private. That ensure noninstantiability and prevents subclassing.
The suggestions of assylias (all Java versions) and Peter Lawrey (>= Java5) are the standard way to go in this case.
However I'd like to bring to your attention that preventing a extension of a static utility class is a very final decision that may come to haunt you later, when you find that you have related functionality in a different project and you'd in fact want to extend it.
I suggest the following:
public abstract MyClass {
protected MyClass() {
}
abstract void noInstancesPlease();
void myMethod() {
...
}
... // More private methods and fields...
}
This goes against established practice since it allows extension of the class when needed, it still prevents accidental instantiation (you can't even create an anonymous subclass instance without getting a very clear compiler error).
It always pisses me that the JDK's utility classes (eg. java.util.Arrays) were in fact made final. If you want to have you own Arrays class with methods for lets say comparison, you can't, you have to make a separate class. This will distribute functionality that (IMO) belongs together and should be available through one class. That leaves you either with wildly distributed utility methods, or you'd have to duplicate every one of the methods to your own class.
I recommend to never make such utility classes final. The advantages do not outweight the disadvantages in my opinion.
You can't mark a class as both abstract and final. They have nearly opposite
meanings. An abstract class must be subclassed, whereas a final class must not be
subclassed. If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.
This is very simple explanation in plain English.An abstract class cannot be instantiated and can only be extended.A final class cannot be extended.Now if you create an abstract class as a final class, how do you think you're gonna ever use that class, and what is,in reality, the rationale to put yourself in such a trap in the first place?
Check this Reference Site..
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.
Thanks..
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 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.