+ 2

Error <identifier expected> in java.

I am not understanding why the code works if we write int x=10; but not works for int x; x=10; https://code.sololearn.com/cvf3upOTq2Nc/?ref=app

18th Jun 2018, 8:27 PM
harshit
harshit - avatar
3 odpowiedzi
+ 2
harshit it because all the data members in the interface is by default public static and imp (final) as you know static data members take memory at class load time. and you cant change the value of variables if the variables is final. now back to your question there are two problem in your code. first 1 int x; x=10 here two concept comes initialization, assignment so what happened first default value provide by compiler to x i.e x=0; now what you do try to change so error come as you know now why because of final variable. 2 test o=new test(); this is static binding.. if not you got an error does not find variable x so do like this display o=new test(); here your code interface display { int x=10; void show(); } public class test implements display { public void show() { System.out.println(x); } public static void main(String[] args) { display o=new test(); o.show(); } }
18th Jun 2018, 8:58 PM
Arun Tomar
Arun Tomar - avatar
+ 1
i believe it's because it's an interface and all values have to be set from the start
18th Jun 2018, 8:57 PM
hinanawi
hinanawi - avatar
+ 1
thanks
18th Jun 2018, 10:01 PM
harshit
harshit - avatar