metichi
metichi

Reputation: 173

Implement an interface in a specific object

Im trying to implement an interface that should affect some objects of a class but not others.

For example lets say this is my code:

public interface KnowsHowToSwim{
    double getHowFast();
}

public class Stable{
    Horse pinky = new Horse(veryFast);
    Horse lightning = new Horse(veryPretty){
        @Override
        public float getPrettynessFactor(){
            return super.getPrettynessFactor()*10000000000
        }
    };
    Horse wetty = new Horse(soCool); <-- This one should KnowHowToSwim
}

Now, i know I can create a new class that extends horse and implements KnowHowToSwim, but since my application will have a lot of fields from different classes that will implement that interface, I was wondering if there was a way to implement the interface in a specific object similar to how Horse lightning overrides its method.

Upvotes: 0

Views: 389

Answers (1)

Gerald M&#252;cke
Gerald M&#252;cke

Reputation: 11132

No you can't.

You wan't something like a trait or mixin, which is not supported in Java. Java8's default methods in interfaces won't work for you because you need a property in the instance (or access to the instance), which is not possible. Default methods have no reference to this.

Further, from a OO perspective, you have to define a separate class, extending Horse and implementing KnowsHowToSwim. All instances of this are a Horse and know-how-swim. Of course you can create only one instance of it.

However you may define a class inside a method body (i.e. a factory method), a.k.a. local class. This class hold referece to all (effectively final) variables in the method. For example:

public static Horse newSwimmingHorse() {

  final Object methodScopeProperty = ...;

  class SwimmingHorse extends Horse implements KnowsHowToSwim {
    double speed;
    double getHowFast(){
      methodScopeProperty.doSomething(); //do you need this access?
      return speed;
    }
  }

  return new SwimmingHorse();

}

But as long as you don't gain any benefits from the accessible method scope I wouldn't recommend it. Use a static inner class instead, optionally with limited visibility or a package-private class. This keeps your code more cohesive.

Upvotes: 1

Related Questions