0
    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?

  • Why would you put data in an interface. Wouldn't an abstract class be better suited for this purpose? – bhspencer Jul 13 '15 at 18:55
  • I was studying interfaces so this situation came into my mind and maybe I would do so because interfaces are lightweight compared to abstract classes. – Shashank Gupta Jul 13 '15 at 18:58
  • consider this http://stackoverflow.com/questions/2430756/why-are-interface-variables-static-and-final-by-default – bhspencer Jul 13 '15 at 18:59

2 Answers2

2

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);
M A
  • 71,713
  • 13
  • 134
  • 174
0

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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Shrinivas Shukla
  • 4,325
  • 2
  • 21
  • 33