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