Why interface variable static final

Why interface variable is static final

  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 variable Name in the class implementing it.

final:

to make them constants.

Let’s say 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 variable,

which is why only one time initialization is permitted.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.javaforlearn;
 
public interface TestInterface 
{
 
	static final int id=007;
 
	void test();
}
 
 
class A implements TestInterface
{
 
	@Override
	public void test() {
 
		System.out.println("Test() is running");
	}
 
 
}
 
class Testmain
{
 
	public static void main(String[] args) 
	{
 
		TestInterface ref=new A();
		ref.test();
 
		// A.id=78; //error --> The final field TestInterface.id cannot be assigned
		System.out.println(A.id);
 
	}
 
 
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *