How to implement contradictory interfaces [duplicate] - java

This question already has answers here:
Java - Method name collision in interface implementation
(7 answers)
Closed 8 years ago.
Shortly I came across an oddity, I can't explain to myself. The real-world problem is already worked around, I'm just curious if there is an satisfying answer I didn't find.
Imagine you have to write a class that implements the following interface from some framework you are using:
interface Interface1 {
String method();
}
So far so good. Now you introduce a second framework and it would be rather useful if your class would implement a second interface:
interface Interface2 {
Long method();
}
That's the point where the problem arises:
class ThatsTheProblem implements Interface1, Interface2 {
public ???? method() {
// ...
}
}
Any ideas?
Just for your information: The real-world problem is based on an abstract-dao-pattern where some entities had Long ids, others had UUID ids.

Short answer: you can't.
What you can do is provide a view that implements one or the other interface. For instance:
public class OnePossibleSolution { // no "implements"
private String interface1Method() {
return "whatever";
}
public Interface1 asInterface1() {
return new Interface1() {
#Override
String method() {
return interface1Method();
}
}
}
// ditto for Interface2...
This is probably the most Java-idiomatic way to solve the problem. It's what Map does when you want to iterate over its elements, for instance. Rather than try to solve the problem of being an Iterable<K>, Iterable<V> and Iterable<Map.Entry<K,V>>, it provides three views:
keySet()
values()
entrySet()
Each of those returns a respective collection, which implements the appropriate Iterable<...> interface.

Two of the components of a method declaration comprise the method signature—the method's name and the parameter types. These methods have the same signature, therefore cannot be implemented by one class.
Remember that in Java, you don't neccesary have to store the result of a method. If your ThatsTheProblem class compiled, and you had a class with this code, to which version of the method would invoke?
ThatsTheProblem ttp = new ThatsTheProblem();
ttp.method();

It is clearly impossible to create one object that implements two conflicting interfaces. However, it is possible for one object to provide two different facades, each implementing conflicting interfaces.
Note here that the two facades refer to common instance variables of the one object so they do, essentially, represent the same object.
public interface Interface1 {
String method();
}
public interface Interface2 {
Long method();
}
public class DiMorph {
String forInterface1 = "Number nine";
Long forInterface2 = 9L;
public Interface1 asInterface1() {
return new AsInterface1();
}
private class AsInterface1 implements Interface1 {
#Override
public String method() {
return forInterface1;
}
}
public Interface2 asInterface2() {
return new AsInterface2();
}
private class AsInterface2 implements Interface2 {
#Override
public Long method() {
return forInterface2;
}
}
}
public void testInterface1(Interface1 i1) {
}
public void testInterface2(Interface2 i2) {
}
public void test() {
DiMorph m = new DiMorph();
testInterface1 (m.asInterface1());
testInterface2 (m.asInterface2());
}

To quote #Andreas, this is simply impossible.
Imagine you have two workers, Alice and Bob, with two managers, Cathy and Dave. Cathy expects Alice to implement the Work() method and return a Java application. Dave, on the other hand, expects Bob to implement the Work() method and return a C++ library. What your question suggests is to introduce a new worker Eric who can do the Work() of Alice and Bob at the same time. What actually happens is that Eric is too overloaded to compile.

Related

Java: polymorphically call super implementation

Suppose I have this:
public class A {
public String foo() { return "A"; }
}
public class B extends A {
public String foo() { return "B"; }
public String superFoo() { return super.foo(); }
}
public class C extends B {
public String foo() { return "C"; }
}
Here, new C().superFoo() returns "A".
Is there a way I can polymorphically make new C().superFoo() invoke B.foo() (and hence return "B") without the need to override superFoo() in C?
I tried with reflection (redefining B.superFoo() like this: return getClass().getSuperclass().getDeclaredMethod("foo").invoke(this)), hoping that with getDeclaredMethod I could reference the exact method implementation in superclass, but I get "C" in that case (hence, polymorphism is applied).
I was searching for a solution that doesn't require me to redeclare superFoo() whenever I add a new subclass to the hierarchy.
TL;DR
Going through the question and comments, it seems like the ask here is to incrementally build up on a behavior. Taking a different perspective, I would prefer Composition over Inheritance in this scenario.
You can use Decorator pattern and compose the instances together; which in turn gives you a reference to the parent's foo() implementation. One of the other benefits is that you can extend/change the behavior at runtime, which is not possible with a static inheritance design.
About Decorator Pattern
Decorator pattern can be used to attach additional responsibilities to an object either statically or dynamically.
Component - Interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent - Defines an object to which additional responsibilities can be added.
Decorator - Maintains a reference to a Component object and defines an interface that conforms to Component's interface.
Concrete Decorators - Concrete Decorators extend the functionality of the component by adding state or adding behavior.
Sample Code
Let's take a Pizza baking process as an example.
Component interface - Defines the contract that a Pizza must be baked.
public interface Pizza {
void bake();
}
ConcreteComponent class - This is your implementation of the interface which can stand alone by itself. It should not extend the Decorator and it appears at the innermost position when the objects are composed together (see client code at the end)
public class VeggiePizza implements Pizza {
#Override
public void bake() {
System.out.println("I'm a Veggie Pizza in the making :)");
}
}
Decorator - Specifies a contract for extending the functionality of the ConcreteComponent.
public abstract class Topping implements Pizza {
private Pizza pizza;
public Topping(Pizza pizza) {
this.pizza = pizza;
}
#Override
public void bake() {
pizza.bake();
}
}
Concrete Decorator - These implementations add to the functionality of the ConcreteComponent by nesting their constructors together (one of the ways to compose!). The concrete decorator can appear anywhere while composing, except for the innermost position (see client code below).
Here we are defining two toppings - Mushroom and Jalapeno.
public class Mushroom extends Topping {
public Mushroom(Pizza pizza) {
super(pizza);
}
#Override
public void bake() {
addMushroom();
super.bake();
}
private void addMushroom() {
System.out.println("Adding mushrooms...");
}
}
public class Jalapeno extends Topping {
public Jalapeno(Pizza pizza) {
super(pizza);
}
#Override
public void bake() {
addJalapenos();
super.bake();
}
private void addJalapenos() {
System.out.println("Adding jalapenos...");
}
}
Client code - How do you compose the ConcreteDecorator and ConcreteComponenttogether?
public void bakePizza() {
Pizza pizza = new Mushroom(new Jalapeno(new VeggiePizza()));
pizza.bake();
}
Notice that we build upon the VeggiePizza by wrapping the objects around with additional behavior from Mushroom and Jalapeno. Here, the ConcreteComponent is the innermost VeggiePizza, while our ConcreteDecorators are Jalapeno and Mushroom.
Note: Constructor composition is only one of the ways to compose. You can compose object together via setters or use a Dependency Injection framework.
Output
Adding mushrooms...
Adding jalapenos...
I'm a Veggie Pizza in the making :)
Following will return B though I've omitted various safety features for the sake of brevity and used commons-lang because you don't want to have to do this stuff yourself! At a minimum, this code assumes every class defines foo() and the you never directly call a.superFoo()! :)
public String superFoo() {
return superXXX("foo");
}
private <T> T superXXX(String name, Object... args) {
Method overriddenMethod = MethodUtils.getAccessibleMethod(getClass(), name);
Iterator<Method> methods = MethodUtils.getOverrideHierarchy(overriddenMethod, EXCLUDE).iterator();
methods.next(); // this is C
Method parentMethod = methods.next(); // This is B;
try {
return (T)parentMethod.invoke(this, args);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
FYI. There may well be an AspectJ/Javassist/Bytebuddy style solution possible as well whereby you can reimplement the superFoo method on all children of A to be super.foo()

I want to follow the interface segregation principle but the class is closed. Is a wrapper the right way?

More than a few times I've found my self working with a class that is closed (I can't modify it) that I wish implemented a nice narrow interface particular to my needs. My client code is supposed to own the interface but I know of no mechanism to announce that this closed class is a implementation of my narrowed interface.
I'm trying to allow this class to be passed in (dependency injected) to my code (composition) but also anything else that can support the narrowed interface. In other languages duck typing makes this trivial. I'm in java though, so I'm expecting to have to write a whole other class just to wrap the closed class to make this happen. Is there a way I'm missing?
Thanks
EDIT to address dupe:
The Interface Segregation Principle offers no mention of the closed class issue which is the point of this question. Please reconsider marking as dupe of this particular question.
This question:
Interface Segregation Principle- Program to an interface, has a good example of the interface segregation principle:
class A {
method1()
method2()
// more methods
method10()
}
class B {
A a = new A()
}
will become
interface C {
method1()
method2()
}
class A implements C{
method1()
method2()
// more methods
method10()
}
class B {
C c = new A()
}
But note how it requires a change to class A. If A is closed to modification how do I accomplish the same thing cleanly?
Depending on the situation, one possibility is to wrap all classes in a wrapper class that exposes the said interface, I mean something like this:
public class UnmodifyableObject {
public void method1();
public void method2();
public void method3();
public void method4();
}
Then you want the interface to look like:
public interface MyInterface {
public void method1();
public void method2();
}
As a solution you can wrap your UnmodifyableObject in a WrappedUnmodifyableObject:
public class WrappedUnmodifyableObject implements MyInterface {
private final UnmodifyableObject unmodifyableObject;
public WrappedUnmodifyableObject(final UnmodifyableObject unmodifyableObject) {
this.unmodifyableObject = Objects.requireNonNull(unmodifyableObject, "unmodifyableObject");
}
#Override
public void method1() {
unmodifyableObject.method1();
}
#Override
public void method2() {
unmodifyableObject.method2();
}
public void method3() {
unmodifyableObject.method3();
}
public void method4() {
unmodifyableObject.method4();
}
}
It does nothing more than delegate all methods, and of course it implements the interface.
A few important things to note are that:
- You should use composition over inheritance, it might look easier to just extend the class, but you do not control that code, it may remove methods or it may even be final.
- This does mean you have to do quite some work.
- If you do not want to do the work yourself, you might need to look into tools to change the bytecode either before execution or before loading the class.
Usage of this object would be via:
UnmodifyableObject unmodifyableObject = someExternalMethodCall();
MyInterface myInterfaceObject = new WrappedUnmodifyableObject(unmodifyableObject);
Use one or more adapters. Adapters are a type of wrapper that changes the interface of the wrapped class without the need to change its source.
class A {
method1()
method2()
// more methods
method10()
}
interface SegregatedI1 {
method1();
}
interface SegregatedI2 {
method2();
method3();
}
class ASegregatedI1Adapter implements SegregatedI1 {
private final A a;
AI1Adapter(A a){
this.a = a;
}
public void method1(){
a.method1();
}
}
Note that A could be an interface or a final class. Also note that an adapter could implement more than one of the segregated interfaces, or you can have separate adapters for each (I'd prefer the latter to keep inline with single responsibility).
Mark Peters suggested simply extending the closed class to avoid the wrapper. Since he hasn't posted an answer based on it I'll write one up.
I normally avoid inheritance in favor of composition as a knee jerk reaction but in this case it really seems to have merit. The main reason being writing a wrapper simply ends up moving the sin of coding to an implementation from the client method into the wrapper. Thus the only thing gained is a level of indirection. If that's all we get and we can find an easier way to get it why not?
Here's some code that slaps a very narrow roleinterface on a very popular and very closed library class: ArrayList.
public class MainClass {
public static void main(String[] args) {
OpenArrayList<String> ls = new OpenArrayList<String>();
ShowClient client = new ShowClient(ls);
ls.add("test1");
client.show();
ls.add("test2");
client.show();
}
}
//Open version of ArrayList that can implement roleinterfaces for our clients
public class OpenArrayList<E> extends ArrayList<E> implements ShowState {
private static final long serialVersionUID = 1L;
}
//Roleinterface for ShowClient
public interface ShowState {
public int size();
public String toString();
}
//Show method programmed to a roleinterface narrowed specifically for it
public class ShowClient {
private ShowState ss;
ShowClient(ShowState ss) {
this.ss = ss;
}
void show() {
System.out.println( ss.size() );
System.out.println( ss.toString() );
}
}
So, if you're going to do Interface Segregation when using a class closed to modification is there a reason not to do it this way?

Is there a pattern for this? Common base class with special actions for certain child classes

I have code that when given a thing it needs to sort out what specific kind of thing it is and then take special actions based on that. The possible classes it could be are all desc
public void doSomething(BaseThing genericThing)
{
if (genericThing instanceof SpecificThing)
{
SpecificThingProcessor stp = new SpecificThingProcessor((SpecificThing) genericThing);
}
else if (genericThing instanceof DifferentThing)
{
DifferentThingProcessor dtp = new DifferentThingProcessor((DifferentThing) genericThing);
}
else if (genericThing instanceof AnotherThing){
AnotherThingProcessor atp = new AnotherThingProcessor((AnotherThing) genericThing);
}
else
{
throw new IllegalArgumentException("Can't handle thing!");
}
}
Is there a pattern or better way of handling this? Unfortunately the operations being performed do not lend themselves to generalization around the BaseThing, they have to be done for each specific class of thing.
The best option I can think of is to abstract the functionality in to an Interface and have each type implement that Interface.
If you add a little more detail about what you're trying to do based on the types, I could make a better suggestion (possibly with some sample code).
EDIT
After the edit, there is definitely a clear way to do this. Each Processor will implement a specific Interface:
public interface IProcessor
{
void Process();
}
public class SpecificThingProcessor : IProcessor
{
public void Process() { /* Implementation */ }
}
public class DifferentThingProcessor : IProcessor
{
public void Process() { /* Implementation */ }
}
public class AnotherThingProcessor : IProcessor
{
public void Process() { /* Implementation */ }
}
Each BaseThing must implement a method to return the specific processor:
public abstract class BaseThing
{
public abstract IProcessor GetProcessor();
}
public class SpecificThing : BaseThing
{
public override IProcessor GetProcessor()
{
return new SpecificThingProcessor();
}
}
public class DifferentThing : BaseThing
{
public override IProcessor GetProcessor()
{
return new DifferentThingProcessor();
}
}
And then your method will simply be:
public void doSomething(BaseThing genericThing)
{
IProcessor processor = genericThing.GetProcessor();
processor.Process();
}
You should define a method in BaseThing to be overridden by the specific Things.
In other words you should be using a virtual function.
The operations being performed are not
being performed on the generic thing.
Depending on its specific type, a
"Producer" class needs to be
instantiated to deal with the correct
type of thing. It is not appropriate
to call the Producer from the
BaseThing subclasses
You can still do: thing.GetProcessor(), and have each thing return the specific processor its used for it. Processors would of course implement a common interface or base class.
For another alternative, this hits my java limit, but I'm sure you should be able to do something along these lines:
store a list/dictionary of type, processor constructor.
Get the type of genericThing instance you are receiving
search for the type in the list and call the corresponding constructor.
The visitor pattern is exactly what you're trying to achieve. However, a "good old-fashioned polymorphism" should do just fine for what you need. For example :
abstract class BaseThing {
abstract public void doSomething();
}
class ThingA extends BaseThing {
public void doSomething() {
System.out.println("ThingA...");
}
}
class ThingB extends BaseThing {
public void doSomething() {
System.out.println("ThingB...");
}
}
class ThingC extends BaseThing {
public void doSomething() {
throw new UnsupportedOperationException("Cannot call this on ThingC");
}
}
and then
class ThingHandler {
public void doSomething(BaseThing thing) {
try {
thing.doSomething();
} catch (UnsupportedOperationException e) {
throw new IllegalArgumentException("Can't handle thing!");
}
}
}
Thus
ThingHandler handler = new ThingHandler();
handler.doSomething(new ThingA()); // -> ThingA...
handler.doSomething(new ThingB()); // -> ThingB...
handler.doSomething(new ThingC()); // -> IllegalArgumentException: Can't handle thing!
You have mentioned "it needs to sort out what specific kind of thing it is", so all you need now is have your BaseThing have an abstract method that will return a Comparator and each ThingA, etc. will implement it and return the proper comparator for the ThingHandler class to sort. Each BaseThing implementation can perform the specific operations or return some kind of value that you'd need in ThingHandler (you could even pass the ThingHandler instance in the BaseThing.doSomething method...)
But if the Visitor pattern is really what you need, here is an example for your need :
interface IThing {
public void accept(ThingHandler handler);
}
interface IThingHandler {
public void visit(ThingA a);
public void visit(ThingB b);
//...
}
class ThingA implements IThing {
public void accept(IThingHandler h) {
h.visit(this);
}
public String getSomeValueA() {
return "Thing A";
}
}
class ThingB implements IThing {
public void accept(IThingHandler h) {
h.visit(this);
}
public String getSomeValueB() {
return "Thing B";
}
}
// ...
class ThingHandler implements IThingHandler {
public void visit(ThingA thing) {
// sort according to ThingA
System.out.println(thing.getSomeValueA() + " has visited");
doSomething(thing);
}
public void visit(ThingB thing) {
// sort according to ThingB
System.out.println(thing.getSomeValueB() + " has visited");
doSomething(thing);
}
private void doSomething(IThing thing) {
// do whatever needs to be done here
}
}
Then
IThingHandler handler = new ThingHandler();
new ThingA().accept(handler); // -> Thing A has visited
new ThingB().accept(handler); // -> Thing B has visited
//...
But since this means maintaining the IThingHandler interface every time a new IThing class is implemented, I prefer suggesting the first modified/simplified implementation of the pattern. However, feel free to adapt the pattern for your need and don't stop yourself because it doesn't exactly look like the described visitor pattern.
The two questions to ask are
"who is responsible to handle the operation?"
"who is responsible to hold the necessary data to perform the operation?"
I usually prefer keeping most of the concrete at the same place and generalize elsewhere; it helps maintaining (i.g. adding and removing features). Although the visitor pattern helps to centralize the operation in a same class...
This sounds like one of the basic ideas of object-oriented programming. You create a superclass that declares doSomething, and then you create subclasses each of which implements it differently. That is:
public class BaseThing
{
abstract public void doSomething();
}
public class SpecificThing extends BaseThing
{
public void doSomething()
{
System.out.println("I'm a SpecificThing!");
}
}
public class DifferentThing extends BaseThing
{
public void doSomething()
{
System.out.println("I'm a DifferentThing!");
}
}
public class AnotherThing extends BaseThing
{
public void doSomething()
{
System.out.println("I'm an AnotherThing!");
}
}
If you really need to pass the "thing" as a parameter for some reason, okay. Do the above, then write:
void doSomething(BaseThing genericThing)
{
genericThing.doSomething();
}
If some of your subclasses can't do the function and should give an error message instead, then just instead of making it abstrct in the supertype, make the supertype do the "invalid" processing, like:
public void BaseThing
{
public void doSomething()
throws IllegalArgumentException
{
throw new IllegalArgumentException("Can't handle this thing");
}
}
The question is almoust the text-book example of Strategy-pattern. You extract the specific behavoir into separate classes that al implement the same interface (with a method like doIt() of something). And then you give each specific class a reference to the "behavior"-object you want it to have.
Bonus:
1) You can change the behavior of an object at runtime by simply given it another "behavior"-object.
2) You don't have to override a method (danger with overriding methods could be class-booming).
This could be dealt with using plain old OO polymorphism before trying to force a pattern onto it.
You don't need to necessarily subclass the processors, you can overload the method declarations in a single Processor class keeping the method name the same but declaring the parameter for the specific type.
void foo(BaseTing ting) { System.out.println("Default " + ting.name); }
void foo(TingA ting) { System.out.println("AA " + ting.name); }
void foo(TingB ting) { System.out.println("BB " + ting.name); }
Java will resolve the method that most closely matches the parameter type, so if you have TingC that extends TingB, then foo(TingB) will be invoked until foo(TingC) is defined in the Processor class.
If you are going to add a lot more actions for each type of thing, i.e. baz(Ting), bar(Ting), bat(Ting) etc. then you may want to split you Processor classes by Ting subtype and use a factory method to create the specific processor a la Strategy pattern.
i.e. BaseProcessor, TingAProcessor, TingBProcessor.
The BaseProcessor would be a good candidate to house the factory method, and should provide default implementations for each of the methods, even if the default implementation is abstract or just throws an exception. The specialised Processors classes should extend from the BaseProcessor and inherit and override the default operations.
You have few options:
* Abstract your functionality into an interface and let other classes implement that interface.
* You could use The Chain of responsibility pattern(consisting of a source of command objects and a series of processing objects).
* You could also use the Strategy design pattern( algorithms can be selected at runtime)

How to use java interfaces with multiple implementing classes

public interface Foo {
}
public class SpecificFoo implements Foo {
}
public interface SomeInterface {
void thisMethod(Foo someKindOfFoo);
}
public class SomeClass implements SomeInterface {
public void thisMethod(Foo someKindOfFoo) {
// calling code goes into this function
System.out.println("Dont go here please");
}
public void thisMethod(SpecificFoo specificFoo) {
// not into this function
System.out.println("Go here please");
}
}
public class SomeOlderClass {
public SomeOlderClass( SomeInterface inInterface ) {
SpecificFoo myFoo = new SpecificFoo();
inInterface.thisMethod(myFoo);
}
}
calling code:
SomeClass myClass = new SomeClass();
SomeOlderClass olderClass = new SomeOlderClass(myClass);
I have an interface (SomeInterface) that several classes call into (such as SomeOlderClass). I have a class that implements the interface, but I want to do type safe operations on the specific implementations that are passed into the generic interface.
As shown in the above code, I really want to able to make another method that matches the specific type passed in to the interface. This doesn't work. I assume it is because the calling code only knows about the interface, and not the implementation with the more specific methods (even though SpecificFoo implements Foo)
So how can I do this in the most elegant way? I can get the code working by adding an if statement in the class implementing the interface (SomeClass):
public void thisMethod(Foo someKindOfFoo) {
// calling code goes into this function
if ( someKindOfFoo.getClass().equals(SpecificFoo.class) )
thisMethod(SpecificFoo.class.cast(someKindOfFoo));
else
System.out.println("Dont go here please");
}
However, this is not elegant, as I have to add if statements everytime I add a new kind of Foo. And I might forget to do so.
The other option is to add SpecificFoo to the SomeInterface, and let the compiler sort out reminding me that I need implementations in SomeClass. The problem with this is that I end up adding quite a bit of boiler plate code. (If someone else implements the interface, they have to implement the new method, as well as any tests)
It seems that there should be another option I am missing, given that Foo and SpecificFoo are related. Ideas?
MORE INFO:
Well I actually worked for a while to try and simplify the question. As I add more details the complexity goes up by quite a bit. But whatever... I think I can explain it.
Basically, I am write a GWT web apps RPC servlet using the command pattern as explained by Ray Ryan in his talk
There are several implementations of it on google code, but many of them suffer this inherit problem. I thought it was a bug in the GWT-RPC code bugreport HOWEVER, as I was implementing further I noticed a similar problem happening purely on the client side, and while in hosted mode. (ie all java, no gwt javascript madness).
So I abstracted the basic ideas to a raw java command line case, and saw the same issue, as described above.
If you follow along with what Ray Ryan discusses, Foo is an Action, SpecificFoo is a specific action I want to call. SomeInterface is the client side RPC service and SomeClass is the server side RPC class. SomeOlderClass is a kind of rpc service that would know about cacheing and whatnot.
Obvious, right? Well as I said, I think all the GWT RPC nonsense just muddies up the waters on the base issue, which is why I tried to simplify it as best I could.
If you need to find out the actual type of an object at runtime, then the design is most probably wrong. That violates at least the Open Closed Principle and Dependency Inversion Principle.
(Because Java does not have multiple dispatch, the thisMethod(Foo)will be called instead of thisMethod(SpecificFoo). Double dispatch could be used to get around the language's limitations, but there might still be some design problem lurking there...)
Please give more information on what you are trying to accomplish. Right now the question does not provide enough information to come up with a right design.
A generic solution is that since the action depends on the runtime type of Foo, that method should be part of Foo so that its implementation can vary depending on Foo's type. So your example would be changed to something like below (possibly adding SomeInterface or other parameters to thisMethod()).
public interface Foo {
void thisMethod();
}
public class SpecificFoo implements Foo {
public void thisMethod() {
System.out.println("Go here please");
}
}
Try using double dispatch: Add a method to the Foo interface that is called by SomeClass#thisMethod. Then place the code in the implementation of this method.
public interface Foo {
public void thatMethod(SomeClass a);
public void thatMethod(SomeOlderClass a);
}
public class SomeClass implements SomeInterface {
public void thisMethod(Foo someKindOfFoo) {
someKindOfFoo.thatMethod(this);
}
}
Sorry, I find the problem description far too abstract to be able to make a recommendation. You clearly have a design issue because you generally should not need to check the type of interface. I will give it a go though... First, I need to make your problem more concrete for my small brain to understand. Instead of Foos, how about Birds?
public interface Bird {
}
public class Ostrich implements Bird {
}
public interface BirdManager {
void fly(Bird bird);
}
public class AdvancedBirdManager implements BirdManager {
public void fly(Bird bird) {
System.out.println("I am in the air. Yay!");
}
public void fly(Ostrich ostrich) {
System.out.println("Sigh... I can't fly.");
}
}
public class ZooSimulation {
public ZooSimulation(BirdManager birdManager) {
Ostrich ostrich = new Ostrich();
birdManager.fly(ostrich);
}
}
public static void main(String[] args) {
AdvancedBirdManager advancedBirdManager = new AdvancedBirdManager();
ZooSimulation zooSimulation = new ZooSimulation(advancedBirdManager);
}
Here, the Ostrich will declare "I am in the air. Yay!" which is not what we want.
OK, so, ignoring the fact that I am failing basic OO here, the problem is that the BirdManager will look for the least-specific method that matches the type that is passed in. So no matter what kind of bird I give it, it will always match fly(Bird). We can put some if checks in there, but as you add more types of birds, your design will degrade further. Here's the tough part - I have no idea if this makes sense within the context of your problem, but consider this refactoring where I move the logic from the manager into bird:
public interface Bird {
void fly();
}
public class BasicBird implements Bird {
public void fly() {
System.out.println("I am in the air. Yay!");
}
}
public class Ostrich implements Bird {
public void fly() {
System.out.println("Sigh... I can't fly.");
}
}
public interface BirdManager {
void fly(Bird bird);
}
public class AdvancedBirdManager implements BirdManager {
public void fly(Bird bird) {
bird.fly();
}
}
public class ZooSimulation {
public ZooSimulation(BirdManager birdManager) {
Ostrich ostrich = new Ostrich();
birdManager.fly(ostrich);
}
}
public static void main(String[] args) {
AdvancedBirdManager advancedBirdManager = new AdvancedBirdManager();
ZooSimulation zooSimulation = new ZooSimulation(advancedBirdManager);
}
Our Ostrich now says the correct thing and the bird manager still treats it as just a bird. Again, bad OO (Ostriches should not have fly() methods) but it illustrates my thoughts.
As long as there are not too many implementations of Foo, I would declare an abstract method in SomeInterface for each subclass of Foo, and have an abstract class forward calls to a default method that is defined for the most general type:
public interface Foo {
}
public class SpecificFoo implements Foo {
}
public interface SomeInterface {
void thisMethod(Foo someKindOfFoo);
void thisMethod(SpecificFoo specificFoo);
void thisMethod(OtherSpecificFoo otherSpecificFoo);
}
public abstract class AbstractSomeInterface {
public void thisMethod(Foo wrongFoo) {
throw new IllegalArgumentException("Wrong kind of Foo!");
}
public void thisMethod(SpecificFoo specificFoo) {
this.thisMethod((Foo) specificFoo);
}
public void thisMethod(OtherSpecificFoo otherSpecificFoo) {
this.thisMethod((Foo) specificFoo);
}
}
public class SomeClass extends AbstractSomeInterface {
public void thisMethod(SpecificFoo specificFoo) {
// calling code goes into this function
System.out.println("Go here please");
}
}
public class SomeOlderClass {
public SomeOlderClass( SomeInterface inInterface ) {
SpecificFoo myFoo = new SpecificFoo();
inInterface.thisMethod(myFoo);
}
}

Practical side of the ability to define a class within an interface in Java?

What would be the practical side of the ability to define a class within an interface in Java:
interface IFoo
{
class Bar
{
void foobar ()
{
System.out.println("foobaring...");
}
}
}
I can think of another usage than those linked by Eric P: defining a default/no-op implementation of the interface.
./alex
interface IEmployee
{
void workHard ();
void procrastinate ();
class DefaultEmployee implements IEmployee
{
void workHard () { procrastinate(); };
void procrastinate () {};
}
}
Yet another sample — implementation of Null Object Pattern:
interface IFoo
{
void doFoo();
IFoo NULL_FOO = new NullFoo();
final class NullFoo implements IFoo
{
public void doFoo () {};
private NullFoo () {};
}
}
...
IFoo foo = IFoo.NULL_FOO;
...
bar.addFooListener (foo);
...
I think this page explains one example pretty well. You would use it to tightly bind a certain type to an interface.
Shamelessly ripped off from the above link:
interface employee{
class Role{
public String rolename;
public int roleId;
}
Role getRole();
// other methods
}
In the above interface you are binding the Role type strongly to the employee interface(employee.Role).
One use (for better or worse) would be as a workaround for the fact that Java doesn't support static methods in interfaces.
interface Foo {
int[] getData();
class _ {
static int sum(Foo foo) {
int sum = 0;
for(int i: foo.getData()) {
sum += i;
}
return sum;
}
}
}
Then you'd call it with:
int sum = Foo._.sum(myFoo);
I can say without hesitation that I've never done that. I can't think of a reason why you would either. Classes nested within classes? Sure, lots of reasons to do that. In those cases I tend to consider those inner classes to be an implementation detail. Obviously an interface has no implementation details.
One place this idiom is used heavily is in XMLBeans. The purpose of that project is to take an XML Schema and generate a set of Java classes that you can use bidirectionally to work with XML documents corresponding to the schema. So, it lets you parse XML into xml beans or create the xml beans and output to xml.
In general, most of the xml schema types are mapped to a Java interface. That interface has within it a Factory that is used to generate instances of that interface in the default implementation:
public interface Foo extends XmlObject {
public boolean getBar();
public boolean isSetBar();
public void setBar(boolean bar);
public static final SchemaType type = ...
public static final class Factory {
public static Foo newInstance() {
return (Foo)XmlBeans.getContextTypeLoader().newInstance(Foo.type, null);
}
// other factory and parsing methods
}
}
When I first encountered this it seemed wrong to bind all this implementation gunk into the interface definition. However, I actually grew to like it as it let everything get defined in terms of interfaces but have a uniform way to get instances of the interface (as opposed to having another external factory / builder class).
I picked it up for classes where this made sense (particularly those where I had a great deal of control over the interface/impls) and found it to be fairly clean.
I guess you could define a class that is used as the return type or parameter type for methods within the interface. Doesn't seem particularly useful. You might as well just define the class separately. The only possible advantage is that it declares the class as "belonging" to the interface in some sense.
Google Web Toolkit uses such classes to bind 'normal' interface to asynchronous call interface:
public interface LoginService extends RemoteService {
/**
* Utility/Convenience class.
* Use LoginService.App.getInstance() to access static instance of LoginServiceAsync
*/
class App {
public static synchronized LoginServiceAsync getInstance() {
...
}
}
}
With a static class inside an interface you have the possibility to shorten a common programming fragment: Checking if an object is an instance of an interface, and if so calling a method of this interface. Look at this example:
public interface Printable {
void print();
public static class Caller {
public static void print(Object mightBePrintable) {
if (mightBePrintable instanceof Printable) {
((Printable) mightBePrintable).print();
}
}
}
}
Now instead of doing this:
void genericPrintMethod(Object obj) {
if (obj instanceof Printable) {
((Printable) obj).print();
}
}
You can write:
void genericPrintMethod(Object obj) {
Printable.Caller.print(obj);
}
Doing this seems to have "Bad design decision" written all over it.
I would urge caution whenever it seems like a good idea to create a non-private nested class. You are almost certainly better off going straight for an outer class. But if you are going to create a public nested class, it doesn't seem any more strange to put it in an interface than a class. The abstractness of the outer class is not necessarily related to the abstractness of a nested class.
This approach can be used to define many classes in the same file. This has worked well for me in the past where I have many simple implementations of an interface. However, if I were to do this again, I would use an enum which implements an interface which would have been a more elegant solution.

Categories

Resources