javainterfacedata-hiding

Data hiding in interface java


    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?


Solution

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