Strange Java interface
At work, I came across the following project in a java project:
Consider interfaces Foo
, Bar
and Baz
as follows:
interface Bar { public int a(); }
interface Baz { public int b(); }
interface Foo extends Bar, Baz { public int c(); }
Now consider the class FooImpl
:
public class FooImpl implements Foo {
private Bar bar;
private Baz baz;
public int a() {
return bar.a();
}
public int b() {
return baz.b();
}
public int c() {
return 0;
}
}
What are the use cases for this type of class hierarchy? It seems to me that this introduces a lot of boilerplate and doesn't add much to the abstraction other than breaking up what might be a large file into smaller files.
source to share
It allows things like this:
Foo foo = new FooImpl();
useBar(foo);
public void useBar(Bar bar) {
bar.a();
}
How useful this is depends on the actual context. Your example code with meaninglessly named classes and methods does not support rational judgment.
It should be noted that yours is FooImpl
actually implemented as some kind of wrapper for instances of Bar
and Baz
. This is not (strictly speaking) a design issue.
source to share
I think this is a workaround for multiple inheritance (which is not allowed in Java). You don't show implementations for Bar
and Baz
, but let them exist:
public class BarImpl implements Bar {
@Override
public int a() {
return 1;
}
}
public class BazImpl implements Baz {
@Override
public int b() {
return 2;
}
}
You also didn't tell us how the attributes are created Bar
and Baz
and are set to FooImpl
, because if they are executed as stated in your question, you will get NullPointerException
both in FooImpl.a()
and FooImpl.b()
. Again, imagine how this could be achieved:
public class FooImpl implements Foo {
private Bar bar; // better if final
private Baz baz; // better if final
// Constructor to properly initialize bar and baz
public FooImpl(Bar bar, Baz baz) {
this.bar = bar;
this.baz = baz;
}
@Override
public int a() {
return bar.a();
}
@Override
public int b() {
return baz.b();
}
@Override
public int c() {
return 0;
}
}
Posting everything:
Bar bar = new BarImpl();
Baz baz = new BazImpl();
Foo foo = new FooImpl(bar, baz);
int one = foo.bar(); // 1
int two = foo.baz(); // 2
In a sense, FooImpl
"inherits" both on BarImpl
and off BazImpl
, although this is achieved through delegation.
source to share