Junior — Middle
Is it possible to override or modify a public method provided by a third-party library?
sobes.tech AI
Answer from AI
In Java, overriding a public method from a third-party library is possible if the class provided by the library is not declared as final and the method is not final. To do this, a subclass is created in which the method is overridden with a new implementation.
If the class or method is final, direct overriding is impossible. In such cases, the following approaches can be used:
- Composition: create your own class that contains an object from the library and implement the desired behavior by delegating calls and modifying them.
- Use of proxies or dynamic proxying (e.g., via java.lang.reflect.Proxy) to intercept calls.
- Use of bytecode manipulation tools (e.g., ByteBuddy, ASM) to modify classes during loading (but this is more complex).
Example of method overriding:
public class LibraryClass {
public void doSomething() {
System.out.println("Original behavior");
}
}
public class MyClass extends LibraryClass {
@Override
public void doSomething() {
System.out.println("Modified behavior");
}
}
Thus, if the library allows inheritance, overriding is possible.