ChatGPT解决这个技术问题 Extra ChatGPT

Why are interface variables static and final by default?

Why are interface variables static and final by default in Java?

You shouldn't put any variables inside Interfaces.
Because interfaces define contracts which can be implemented in various ways. The value of a variable is implementation.
We certainly can when we know all the classes implementing the interface have some constant variables(Field names for instance).
Is it a good idea to make a variable in a class an instance of the interface that the class implements? I have heard this before.
Answer by Arun Raaj (answered Apr 24 '18 at 12:30) and comment by denis (Aug 17 '17 at 21:02) correctly identify Multiple Inheritance as the main issue...

D
Dave Jarvis

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


Note that abstract classes cannot be instantiated "in their own right" neither and those can have instance variables.
This explanation for the static modifier is completely spurious. A class's public instance variables are part of its interface and there's no reason why they shouldn't be abstracted in a Java interface, just like instance methods. It doesn't matter that a Java interface can't be instantiated directly - you can still have instances of classes that implement the interface and it's sensible to require that they have a certain public instance variable. As for the part about final, that doesn't offer an explanation at all - it just describes what final means.
The quote above is better in context. The reason it gives is that "interface variables are intended to be Java constants". The quote was just elaborating on why such a constant would be static and final. That's true, but the real question is: why aren't variables allowed as part of the actual interface (ie. specifying the names and types of non-private members that must occur in an implementing class). If they wanted special "interface constants", they could have used new syntax, or just decided that any variables actually defined in an interface are interface constants.
Interfaces cannot have instance variables in order to avoid multiple inheritance of state problems. See docs.oracle.com/javase/tutorial/java/IandI/… . A class cannot extend more than one class due to the same reason.
How is default methods introduced and they do have instance, yet instance variable is not supported...
N
Nutan

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.


K
Kasun Siyambalapitiya

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!!!


Of course an instance variable would be accessible if it was allowed in a Java interface. A class would implement the interface, declaring the instance variable (as required by the interface). Its constructor (or other method) sets the instance variable. When an instance of the class is instantiated, you will be able to access its instance variable.
Java allows static methods with bodies to exist in an interface. Those could access the static variables. They just cannot change them, which means the static functions cannot store any data
M
Malvon

(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.


A
Amir Afghani

Because anything else is part of the implementation, and interfaces cannot contain any implementation.


then what is the reason for final.
To indicate that its a constant. Java doesn't have a const keyword. static final is how you declare constants.
Since Java 8, they can contain an implementation, but it's highly recommended to not use it if you do not need backwarts compatibility. :)
A
Asif Mushtaq
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.


In fact, without the specification "A.x" it would not even compile", so it is actually safe to use variables (which implicitly are public static final) in interfaces .
I disagree with the answer, as @Marco said it wouldn't even compile. I didn't find any other disadvantage so far, maybe just that you don't see written static final before the variable that actually is static and final.
A
Arun Raaj

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


R
RubyDubee

static - because Interface cannot have any instance. and final - because we do not need to change it.


"we do not need" == "we aren't allowed", don't mix the meanings.
s
spyro

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


V
Vishal Sheth

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.


A
Anssi

An Interface is contract between two parties that is invariant, carved in the stone, hence final. See Design by Contract.


G
Giri

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.


This is plain wrong. The compiler is not going to complain unless you make it private or protected. Under the hood, as others have already mentioned, they're converted to public static final. And I guess it's pretty obvious why. Because interface is meant to dictate behavior, not state.
u
user3889476

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.


s
srikant

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.


S
Saidolim

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));
    }
}

W
Watachiaieto

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