Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extend an object returned by a static method in java

I have the following problem.

I have a static method of a library class (that I cannot change) like this:

Loader.loadModel()

it returns an object of type Model.

I have also created a subclass of Model called ExtendedModel that adds to Model some methods and some fields.

I cannot do:

ExtendedModel m = Loader.loadModel() //compiler error
ExtendedModel m = (ExtendedModel) Loader.loadModel() //ClassCastException at runtime

because in Java you cannot assign a object of a super class to a sub class.

However, I was wondering: which is the best way in which I could add methods and fields to a object returned by Loader.loadModel()

like image 435
user975176 Avatar asked Dec 05 '25 15:12

user975176


1 Answers

Although you have added a new class, you do not have a new instance of that class. In order to be able to use the additional methods and fields of a model, you need to have an instance of ExtendedModel; the Loader.loadModel() returns an instance of the "regular" Model, causing the problem.

To extend functionality of an object you need to write a wrapper class. A wrapper typically takes an object of the "base" class, delegates the base functionality to it, and adds some methods/variables of its own:

public class ExtendedModel : Model {
    private final Model wrapped;
    public ExtendedModel(Model model) { wrapped = model; }
    private int addedField = 123;
    // Methods of the Model that you did not change simply forward the calls:
    public void doSomething() { wrapped.doSomething(); }
    public int calculateSomething() { return wrapped.calculateSomething(); }
    // Extended methods do whatever you need them to do:
    public int getAddedField() {return addedField;}
    public void increment() {addedField++;}
}

Now you can create an instance of ExtendedModel like this:

ExtendedModel m = new ExtendedModel(Loader.loadModel());
like image 145
Sergey Kalinichenko Avatar answered Dec 07 '25 03:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!