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
- Item 16: Favor composition over inheritance
- Item 17: Design and
document for inheritance or else prohibit it
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