Extending a class created by another class

I work with the Java API used for "macros" that automate a piece of software. The API has, among other things, the classes Simulation (global state) and FunctionManager . I can do nothing to change these classes.

I would like to make a BetterFunctionManager class that extends FunctionManager , because the latter does not have some useful functions. But I do not know how to do this, because FunctionManager cannot be created directly. It should be obtained from Simulation , for example:

 Simulation simulation = getCurrentSimulation(); FunctionManager functionManager = simulation.getFunctionManager(); 

Note that Simulation cannot be created directly; it must be obtained through getCurrentSimulation() (the current simulation is determined at run time by the macro interpreter).

I can not miss; The following throws a ClassCastException:

 BetterFunctionManager betterFunctionManager = simulation.getFunctionManager(); 

How can I build a BetterFieldFunctionManager ?

+8
java constructor extends
source share
3 answers

Disclaimer: I am still very naive in design. Just an offer. use delegation template

 public class BetterFunctionManager{ private FunctionManager fm; public BetterFunctionManager(FunctionManager fm){ this.fm = fm; } existingMethods(){ fm.existingMethods(); } newMethods(){ // new implementation } } 

Disadvantages:

need to wrap all FunctionManager methods

Advantage:

no need for any other place. just change how

 BetterFunctionManager betterFunctionManager = new BetterFunctionManager (simulation.getFunctionManager()); 
+4
source share

What you found is called the Expression Problem , and I'm afraid that your most sensible option to attack it with pure Java is StinePike’s suggestion of using composition and delegation

If you are able to choose a tool for the task, I would recommend that you take a look at Clojure Protocols . They offer a really good solution to the expression problem (see A very good explanation here Solving the expression problem with Clojure ), and if I'm not mistaken, if you finish coding your solution in clojure, you can compile it into a java class and use it in your java application

+2
source share

Since your options are limited due to class structures, how about creating a FunctionManagerUtility class instead of a BetterFunctionManager. In the FunctionManagerUtility class, you can add methods to add useful functions using the FunctionManager object as input.

+1
source share

All Articles