I thought private methods in a class cannt be overridden. But chack this code and please explain. Or am I missing anything? class Base { private void method(){} } class Sub extends Base { public static void main(String args[]) { //call the method() } void method() { System.out.println("Inside Sub"); } }
Gauthaman Ravindran
Greenhorn
Joined: Jul 15, 2000
Posts: 12
posted
0
When you override a method, the new method cannot have an access modifer that is *more* private than the parent method. In this case, the parent method is private, and the child method is default, so this is okay. That being said, I'm not sure if this is really "overriding". Since the private method in the parent is not available to the child class, it seems that you would not really be overriding the method here. Instead, you would simply be making a new method which coincidentally has the same name as a method in the parent class. The two methods would not be otherwise related. I'm sure someone will clarify this for both of us. Gauth
Junaid Bhatra
Ranch Hand
Joined: Jun 27, 2000
Posts: 213
posted
0
Yes private methods cannot be overriden. Private methods, as the name suggests, cannot be seen outside of the class. Hence you are free to define methods with the same name and signature in deriving classes. Then these 2 methods will be un-related. What this also means that the derived class method does not have the usual restriction of checked exceptions...i.e. it's free to throw any checked exception irrespective of the base class method. Also note that private methods do NOT take part in polymorphism. For eg. consider the code below:
The above code prints out "Inside Base". [This message has been edited by Junaid Bhatra (edited July 29, 2000).]