I have object1 of class Class1. I would like to extend class Class1 to Class2 adding one method and then create object2 of Class2 that would behave in all methods exactly as object1, except that now it would have an additional method.
Class1 object1 = new Class1();
Class2 object2 = new Class2(object1);
object2.oldMethod();
object2.newMethod();
object1.oldMethod should have exactly the same behaviour as object2.oldMethod. A stupid way would be to write a script that would generate the new class with all more than 100 inherited methods from Class1:
public class Class2 {
private final Class1 object1;
public Class2(Class1 object1) {
this.object1 = object1;
}
public void oldMethod() {
object1.oldMethod();
}
...
public void newMethod() {
...
}
}
But I would like to be smarter than that. How?
EDIT: I am sorry for not making it more explicit. I get object1 from some 3rd party, this object comes with some internal state - say some setters were ran on it before. I need to get object2 with the same internal state (this is what I mean by the same behaviour when a method is executed). I cannot just extend Class1, then get object2 from Class2. How will object2 know about the state of object1? I do not know the internal state (variables, arrays, fields) of the object1.
EDIT2: I want to wrap object1, but do not want to have to write 100 wrapper methods for what stays the same.