I have class like:
MyClass extends MyAbstractClass implement myInterface1, myInterface2,...
I need create new class with additional fields:
MyType1 field1;
MyType2 field2;
.......
Seems that correct create new class that will wrap MyClass like:
MyWrapClass {
MyClass myClass=new MyClass(...);
MyType1 field1;
MyType2 field2;
.....
But MyWrapClass used as type myInterface1 or myInterface2!
So question is: should I declare all methods that are needed for interfaces myInterface1, myInterface2 in MyWrapClass ? Or exists another way? Thanks.
Basically, there are two ways. First one is to extend the base class:
public class MySubClass extends MyClass {
private MyType1 field1;
private MyType2 field2;
....
The second option is to use composition:
public class MySubClass implements myInterface1, myInterface2 {
private MyClass delegate;
private MyType1 field1;
private MyType2 field2;
// for all methods in myInterface1, myInterface2
public SomeType method1() {
return delegate.method1();
}
...
}
The second option is recommended by many Java Gurus:
Josh Bloch's book Effective Java 2nd Edition
Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.
See also http://en.wikipedia.org/wiki/Composition_over_inheritance
Composition over inheritance can simplify the initial design of Business Domain classes and provide a more stable business domain in the long term. Its advantage over inheritance is a more thorough isolation of interests than can be described by a hierarchy of descendant classes. Additionally, inheritance models are often contrived during the definition of business domain classes in order to make sense of the information in the problem domain and do not necessarily reflect the true relationship of various system objects.
P.S.: auto-generating code for composition is supported by some of modern IDEs
Don't wrap, just subclass:
class MySubClass extends MyClass {
MyType1 field1;
MyType2 field2;
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With