Can we change the value of an interface field?

No, we can’t change the value of an interface field because interface fields are final and static by default.

Example

interface FinalTest{
    String website = "w3spoint.com";
}
public class Main implements FinalTest{
    void show(){
		System.out.println(website);
	}
	public static void main(String args[]){
		//creating object of Main Class
		Main obj = new Main();
		obj.show();
	}
}

Output

w3spoint.com

We will get compile time error, if we try to change the interface field value. Example

interface FinalTest{
    String website = "w3spoint.com";
}
public class Main implements FinalTest{
    void show(){
        website = "java.com";
		System.out.println(website);
	}
	public static void main(String args[]){
		//creating object of Main Class
		Main obj = new Main();
		obj.show();
	}
}

Output

Main.java:6: error: cannot assign a value to final variable website
        website = "java.com";
        ^
1 error

Java interview questions on final keyword

Please follow and like us:
Content Protection by DMCA.com