This post originated from an RSS feed registered with Java Buzz
by Javin Paul.
Original Post: Can we Override Private Method in Java? Inner Class?
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
No, you cannot override private methods in Java, private methods are non
virtual in Java and access differently than non-private one. Since method
overriding can only be done on derived class and private methods are not
accessible in subclass, you just can not override them. By the way, one more
possibility of overriding private methods in inner class, since private methods
are accessible in inner class, and that’s why it is one of the tricky
java interview question. Anyway this will also not work because private
methods are bonded during compile time and only Type (or Class) is used to
locate a private method. For Example in below code where it looks like that nested
class is overriding private method, but if you call privateMethod() with a
type of super class but object of sub class, it will only execute privateMethod() declared
in parent class, which is not exactly method overriding. Had private method
overridden that it would have called method from child class. By the way,
compiler will not complain, it will treat method with exact same signature in
child class as separate method, and this is known as method hiding in Java.