If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error. Overriding can be very confusing because it involves the JVM taking action seemingly independently. Just remember that without access to the method[s] in the superclass in other words, for all methods marked private , the subclass can't invoke or override the said method[s] because it can't inherit them to do so.
No we cannot override Private methods, but there is a case where we can override private methods too i. Inner class. In this you are not overriding this fun in the Child class you are defining a new method with the same name but if you try to use override on the top of fun of Child class than you will get compile time error because you are forcing to override this fun else you are just redefining the new fun in Child class. Can I override a private method in Java?
Question I know I can use reflection to invoke a private method, and to get or set the value of a private variable, but I want to override a method. Private methods are implicitly final. You can't override a private method. Get answers to millions of questions and give back by sharing your knowledge with others. Sign up for an account. Close Sign up.
One way to look at it is to ask yourself whether it would be legal to write super. The derive class can not access the private method on the ancestor. It is erroneous to convolute visibility with inheritance because they don't always match up. You cannot override a private method. It isn't visible if you cast A to B.
You can override a protected method, but that isn't what you're doing here and yes, here if you move your main to A then you would get the other method. I would recommend the Override annotation when you intend to override,. Get Free Tutorials by Email Email:. Advertisements help running this site for free. To view the content please disable AdBlocker and refresh the page.
Labels: core java interview question answer , object oriented programming. Anonymous August 30, at AM. Chowdary February 9, at AM. Unknown December 27, at AM. Anonymous January 21, at PM. Anonymous June 27, at AM. Rajendra Mahakali May 21, at AM. Anonymous September 3, at AM. Unknown March 31, at AM. Unknown October 24, at PM. Anonymous October 12, at AM. Unknown May 22, at AM. Sujit Pingale!!!
0コメント