Hi Ranchers, I was working on enum and found this observation. When we have to override a general behaviour for a specific behaviour we override the default implementation with our implementation but the rules of overridng applies here that is if the generic method signature is public we cannot make the overriden implementation private. Agreed. But when i have a generic method declared to be private but i override this with public method my overriden method does not execute, instead the generic method gets executed. Kindly find the code snippet below for reference.
Thanks and Regards, Pradeep [ November 03, 2008: Message edited by: Pradeep Kumar ]
The answer is very simple i guess. You 'cannot' override private methods. What you think as override is not override at all.
Joined: Sep 11, 2007
Ok, got that private methods cannot be overriden. But why is the behavious differennt when we use inharitance. i.e, when we have a method declared as privarte in super class and the same in the subclass but with public access modifier we cannot use the superclass reference to call the method even though the object is of sub class. Also if we use the subclass reference the method implementation of the sub class will be called. But why is the similar behaviour not found when working with enum.My doubt is if the jvm treats enum as a constant(like Superclass reference) and try invoking the private method it should fail at compile time and if the jvm treats enum constant(like a subclass type reference) it should ivoke the constant specific method implementation right??
Thannks and Regards, Pradeep [ November 03, 2008: Message edited by: Pradeep Kumar ]
Difficult to understand your point about inheritance, but you are not using inheritance. You are writing a new method, which is hiding. If you call the method from the superclass reference, you get the method in the superclass. If you give the "default" method non-private access and put the @Overrride annotation on the subclass methods it compiles and then you are using inheritance and it prints "Cold coffee."
Joined: Sep 11, 2007
I agree to your point that if i have the default method as non private it will be overriden by the enum constant's method implementation. Perfect.
But i want to know that when is write Coffee.COLD.printPreferredCoffee(); statement, does the jvm call the method using the reference or the enum constant. I can demonstrate the inheritance thing that i mentioned.