Change a Class without changing it’s code?

I have the following problem, i Need to change a Class that i have to Import from outside, But i can only Import and not Access it to change it. I also can‘t (could, But is much more complicated Solution) extend a new class from this class, because this class is used in another class, where i still Need it to go through to make everything go how i Need it. And i just Need to add a Variable and add a new function. Don‘t Need to change other things (as far as i know right now). So, in short : I Need to add things to a Class i can‘t Access, But i can‘t extend from it. What can i do?

Can I ask why you can’t access it?

It is an Imported class within one of processings internal classes and is from org.eclipse, so i can’t Access it to change it… (if i‘m not mistaken on how that works :sweat_smile:)

Not sure if this is what you want, but you can create you own class class myClass extends importedClass {} and create your custom functions.

As i said, i can‘t (could, But would have me Chance around 3000 Lines of code…) extend a new class from the imported one :sweat_smile:

One approach is to use the Decorator pattern to add without changing. This very much depends on all the specifics of what you are trying to do that you aren’t sharing, so I can’t give you more detail without more information, but the basic idea of composition is to stick your unchangeable object as a property in a wrapper class, and add your one variable and one new function there. Whether you then need to forward everything from the underlying object or implement it as an interface etc. again depends on the details of what you are try to do.

But, to start with a basic wrapper approach (no interface forwarding):

class MyClass {
  public CantChange wrapped;
  private int val = 3;
  MyClass(CantChange wrapped){
    this.wrapped = wrapped;
  public int getVal() {
    return val;

CantChange unchangeable = new CantChange();
MyClass mc = new MyClass(unchangeable);

mc.getVal();  // 3

mc.wrapped.normalMethod();  // as usual for a CantChange

functionThatTakesACantChange(mc.wrapped);  // as usual for a CantChange
1 Like

Thanks a lot :sweat_smile: that’s what i was looking for :blush: