As others have said, no, you cannot override a method at runtime. However, starting with Java 8, you can take a functional approach. Function is a functional interface that allows you to treat functions as reference types. This means that you can create several of them and switch between them (dynamically) a-la pattern.
Let's look at an example:
public class Example { Function<Integer, Integer> calculateFuntion; public Example() { calculateFuntion = input -> input + 1; System.out.println(calculate(10)); // all sorts of things happen calculateFuntion = input -> input - 1; System.out.println(calculate(10)); } public int calculate(int input) { return calculateFuntion.apply(input); } public static void main(String[] args) { new Example(); } }
Output:
eleven
nine
I donβt know under what circumstances and design you intend to override, but the fact is that you replace the behavior of the method, which does the override.
user1803551
source share