Override private method in java
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,
class A extends B {
@Override
public void don() { // <-- will not compile if don is private in B.
System.out.println("hoho public");
}
}
In this case why didn't compiler provide an error for using
t.don()
which isprivate
?
The Java Tutorials: Predefined Annotation Types says (in part)
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with
@Override
fails to correctly override a method in one of its superclasses, the compiler generates an error.
How to override private method
It is not possible to override private methods, neither in Kotlin nor in Java.
Reflection does not help here. Private methods are dispatched statically, not dynamically -- that is, the correct implementation is chosen at compile time, not runtime.
See also:
- Override "private" method in java
- Overriding private methods in Java
To "achieve what you want", you should go another route -- if the API you use foresees extension, it will likely offer that in one way or another.
Can I override a private method in Java?
Private methods are not inherited and cannot be overridden in any way. Whoever told you you can do it with reflection was either lying or talking about something else.
However, you can access the private method getInt
of whatever subclass is invoking printInt
like so:
public void printInt() throws Exception {
Class<? extends SuperClass> clazz = getClass();
System.out.println("I am " + clazz + ". The int is " +
clazz.getMethod("getInt").invoke(this) );
}
This will have the effect of the subclass' getInt
method being called from the superclass' printInt
.
Of course, now this will fail if the subclass doesn't declare a getInt
, so you have to add a check to be able to handle "normal" subclasses that don't try to "override" a private method:
public void printInt() throws Exception {
Class<? extends SuperClass> clazz = getClass();
// Use superclass method by default
Method theGetInt = SuperClass.class.getDeclaredMethod("getInt");
// Look for a subclass method
Class<?> classWithGetInt = clazz;
OUTER: while( classWithGetInt != SuperClass.class ){
for( Method method : classWithGetInt.getDeclaredMethods() )
if( method.getName().equals("getInt") && method.getParameterTypes().length == 0 ){
theGetInt = method;
break OUTER;
}
// Check superclass if not found
classWithGetInt = classWithGetInt.getSuperclass();
}
System.out.println("I am " + classWithGetInt + ". The int is " + theGetInt.invoke(this) );
}
You still have to change superclass code to make this work, and since you have to change superclass code, you should just change the access modifier on getInt
to protected
instead of doing reflection hack-arounds.
Overriding private methods
3: Teacher can override existing private methods of Person.
That's wrong.
Private methods/fields of super class are not visible/inherited to sub classes. So, You can't override them.
Try it with an example
“overriding” private methods with upcasting call in java
A private method can't be overridden by sub-classes. If the sub-classes declare a method with the same signature as a private method in the parent class, the sub-class method doesn't override the super-class method.
When you call method d()
, if d()
is not overridden by the sub-class, the executed method is PrivateOverride
's d()
. When that method calls f()
, it sees the private f()
method defined in PrivateOverride
. Since that method is not overridden (as it can't be), it calls that method and not the f()
method of the sub-class.
If d()
is overridden, the d()
method of the sub-class DerivedWithD
is executed. When that method calls f()
, it calls the f()
method of DerivedWithD
.
If f()
is no longer private, the f()
method in the sub-classes now overrides the f()
method of the super-class, and therefore f()
of the sub-class is executed in both cases.
Related Topics
Stream Filter of 1 List Based on Another List
Create File with Given Size in Java
Java - Regular Expression Finding Comments in Code
Java String Array: Is There a Size of Method
Netbeans How to Set Command Line Arguments in Java
How to Run All Tests Belonging to a Certain Category in Junit 4
Production Settings File for Log4J
Does Variable = Null Set It for Garbage Collection
What Is the Use of Pattern.Quote Method
How to Ignore Pkix Path Building Failed: Sun.Security.Provider.Certpath.Suncertpathbuilderexception
Why Should I Use Concurrent Characteristic in Parallel Stream with Collect
How to Provide Pagination Support to a Jtable in Swing
Strange Behavior of Class.Getresource() and Classloader.Getresource() in Executable Jar
Are Thread.Sleep(0) and Thread.Yield() Statements Equivalent