Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap class in java and save interface?

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.

like image 226
user710818 Avatar asked Apr 04 '12 15:04

user710818


2 Answers

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

like image 152
Eugene Retunsky Avatar answered Oct 05 '22 21:10

Eugene Retunsky


Don't wrap, just subclass:

class MySubClass extends MyClass {
    MyType1 field1;
    MyType2 field2;
    ...
like image 45
Bohemian Avatar answered Oct 05 '22 21:10

Bohemian