-4

I am learning interfaces in java and the source from which i am learning clearly says that static variables do not get inherited. But for some reason, I am able to access that static variable without adding the interface name before it. I want to know why is this happening and an in depth explanation of whats going on !!!? plzz help

    class StaticMethods {
    public static void main(String [] com) {
       TourClient t = new TourClient(); // i made this a class variable in place of interface variable just for demonstration
       t.check();
    }
}
interface Tour {

    ///This stuff is just for display, doesn't play a role
    static float minimalCost = 50000;
    static float maximumCost = 1000000;

    static float recommendedRating = 3.9f;
    static int minimumVisitingPlaces = 4;

}

interface DubaiTour extends Tour {
    static float Rating = 4.4f; 
}

class TourClient implements DubaiTour{

    void check() {
        System.out.println(Rating); // This is not giving me any errors!!
    }
}

NOTE :- I found a stack overflow page Does static variable inherited? , but this does not explain in depth why is this happening, which doesn't help me

Community
  • 1
  • 1
mitesh
  • 235
  • 3
  • 11

2 Answers2

1

Static variables are inherited.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
0

Once again - static variables are inherited - BUT you shouldn't use them. The reason why is, if you build your program. For optimization, your TourClient class variables get substituted with the constants. The line System.out.println(Rating) gets replaced with System.out.println(4.4) - all is well. If you edit your interface and change a variable to, say, 5.5, it won't get updated in your TourClient class. It will probably still print 4.4. When you use static variables in an interface, you need to recompile EVERYTHING. Not just the files you change.

older coder
  • 614
  • 1
  • 4
  • 12