interface My{
int x = 10;
}
class Temp implements My{
int x = 20;
public static void main(String[] s){
System.out.println(new Temp().x);
}
}
This prints the result as 20. Is there any way that I can access the x that belongs to the interface in the class?
You need to do an explicit cast to the interface type:
System.out.println(((My)new Temp()).x);
Note however that x
is not bound to any instance of My
. Interface fields are implicitly static
and final
(more of constants), meaning the above can be done using:
System.out.println(My.x);
You can always use this.
interface My {
int x = 10;
}
class Temp implements My {
int x = 20;
public static void main(String[] s) {
System.out.println(new Temp().x); // 20
System.out.println(My.x); // 10
}
}
fields of an Interface
are always static.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.