I have an Inreface say
public interface myInterfacy {
String kilogramToGram();
Long litresTomiliLitres();
String inchesToMillimeters();
String ouncesToGrams();
}
I need to have multiple implementaton of this interface but I want the partial implementation of this inteface on different implementation,
As:
public class A implements myInterfacy {
public String kilogramToGram(){
//code
};
I don't want to give the definition of other methods.
}
public class B implements myInterfacy {
Long litresTomiliLitres(){
//code
};
I don't want to give the definition of other methods.
}
I thought that I can di it via using an abstract class, but I wonder If any other good approach is possible.
The answer is relatively simple but has many options.
You could
Make a number of partial interfaces and the one that "does it all" implements them all (not great)
You could make a number of "dummy" interfaces which throw an exception of unimplemented functionality. So, every proxy class would implement the full interface but throw runtime errors on unsupported methods (also not great)
Simply do nothing - literally. Implement the full interface and provide empty bodies (also really not great)
Or, you could encapsulate the functionality with a specific proxy to provide the given functionality.For example,
class FullyFunctional {
public void foo() {...}
public void bar() {...}
}
class PartiallyFunctional {
FullyFunctional ff;
public PartiallyFunctional(FullyFunctional ff) {
this.ff = ff;
}
// No foo...
public void bar() { ff.bar(); }
}
One way to do this, is with a convenience base class. This is however not really a good idea, because you won't get compile type checking to help ensure that you don't call unimplemented method.
public interface Converter {
public String kilogramToGram();
public long litresTomiliLitres();
public String inchesToMillimeters();
public String ouncesToGrams();
}
public abstract class AbstractConverter implements Converter {
#Override
public String kilogramToGram() {
throw new UnsupportedOperationException();
}
#Override
public long litresTomiliLitres() {
throw new UnsupportedOperationException();
}
#Override
public String inchesToMillimeters() {
throw new UnsupportedOperationException();
}
#Override
public String ouncesToGrams() {
throw new UnsupportedOperationException();
}
}
public final class A extends AbstractConverter {
#Override
public String kilogramToGram() {
//code
}
}
Follow interface-segregation-principle
Divide fat interface into granular small interfaces
Implement only require interface
One extreme case: I will declare four interfaces for four methods
public interface IKGToGram {
String kilogramToGram();
}
public interface ILitersToMilliLeters{
Long litresTomiliLitres();
}
public interface IInchesToMilliMeters{
String inchesToMillimeters();
}
public interface IOunceToGrams{
String ouncesToGrams();
}
Now you can implement whatever interface set you want to.
Have a look at explanation about interface segregation concept:
Interface Segregation Principle- Program to an interface
Related
Suppose I have two interfaces:
public interface I1
{
default String getGreeting() {
return "Good Morning!";
}
}
public interface I2
{
default String getGreeting() {
return "Good Afternoon!";
}
}
If I want to implement both of them, what implementation will be used?
public class C1 implements I1, I2
{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
}
This is a compile-time error. You cannot have two implementation from two interfaces.
However, it is correct, if you implement the getGreeting method in C1:
public class C1 implements I1, I2 // this will compile, bacause we have overridden getGreeting()
{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
#Override public String getGreeting()
{
return "Good Evening!";
}
}
I just want to add that even if the method in I1 is abstract, and default in I2, you cannot implement both of them. So this is also a compile-time error:
public interface I1
{
String getGreeting();
}
public interface I2
{
default String getGreeting() {
return "Good afternoon!";
}
}
public class C1 implements I1, I2 // won't compile
{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
}
This is not specific to the question. But, I still think that it adds some value to the context. As an addition to #toni77's answer, I would like to add that the default method can be invoked from an implementing class as shown below. In the below code, the default method getGreeting() from interface I1 is invoked from an overridden method:
public interface I1 {
default String getGreeting() {
return "Good Morning!";
}
}
public interface I2 {
default String getGreeting() {
return "Good Night!";
}
}
public class C1 implements I1, I2 {
#Override
public String getGreeting() {
return I1.super.getGreeting();
}
}
If a class implements 2 interfaces both of which have a java-8 default method with the same signature (as in your example) the implementing class is obliged to override the method. The class can still access the default method using I1.super.getGreeting();. It can access either, both or neither. So the following would be a valid implementation of C1
public class C1 implements I1, I2{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
#Override //class is obliged to override this method
public String getGreeting() {
//can use both default methods
return I1.super.getGreeting()+I2.super.getGreeting();
}
public String useOne() {
//can use the default method within annother method
return "One "+I1.super.getGreeting();
}
public String useTheOther() {
//can use the default method within annother method
return "Two "+I2.super.getGreeting();
}
}
There is a case where this actually works according to the resolution rules. If one of the interfaces extends one of the others.
Using the example from above:
public interface I2 extends I1 {
default String getGreeting() {
return "Good Afternoon!";
}
}
The result would be:
Good Afternoon!
However, I believe this is going to be a big problem. The whole reason for default interfaces is to allow library developers to evolve apis without breaking implementers.
Understandably they don't allow the methods to compile without the inheritance structure via extension because a library developer could potentially hijack behavior.
However, this has the potential to be self defeating. If a class implements two interfaces that are not related from a hierarchical view, but both define the same default method signature, then the class that extends both interfaces will not compile. (as demonstrated above)
It is conceivable that two different library developers could decide to add default methods at different times using common signatures; in fact it is probable that this will happen in libraries that implement similar concepts such as math libraries. If you happen to be the sorry soul implementing both interfaces in the same class you will be broken on update.
I believe the rule is that the class implementing the duplicate default methods 'must' override the implementation.. The following compiles and runs fine...
public class DupeDefaultInterfaceMethods {
interface FirstAbility {
public default boolean doSomething() {
return true;
}
}
interface SecondAbility {
public default boolean doSomething() {
return true;
}
}
class Dupe implements FirstAbility, SecondAbility {
#Override
public boolean doSomething() {
return false;
}
}
public static void main(String[] args) {
DupeDefaultInterfaceMethods ddif = new DupeDefaultInterfaceMethods();
Dupe dupe = ddif.new Dupe();
System.out.println(dupe.doSomething());
}
}
> false
This is the simple way:
public interface Circle{
default String shape() {
return "Circle drawn...";
}
}
public interface Rectangle{
default String shape() {
return "Rectangle drawn...";
}
}
public class Main implements Circle, Rectangle{
#Override
public String shape() {
return Circle.super.shape();// called using InterfaceName.super.methodName
}
}
Output:
Circle drawn...
Default methods in Java 8 can be viewed as a form of multiple inheritance (except that attribute can not be inherited).
The main motivation behind default methods is that if at some point we need to add a method to an existing interface, we can add a method without changing the existing implementation classes. In this way, the interface is still compatible with older versions. This is a cool feature. However, we should remember the motivation of using Default Methods and should keep the separation of interface and implementation.
interface First{
// default method
default void show(){
System.out.println("Default method implementation of First interface.");
} }
interface Second{
// Default method
default void show(){
System.out.println("Default method implementation of Second interface.");
} }
// Implementation class code
public class Example implements First, Second{
// Overriding default show method
public void show(){
First.super.show();
Second.super.show();
}
public static void main(String args[]){
Example e = new Example();
e.show();
} }
I want to validate my domain objects before I pass them on to a other part of the system. All the objects that I want to validate share the same interface. The problem is that I can't figure out how to write this in a good way. I don't want to move the validation inside my value object. But I don't want to be forced to do a instanceOf-check either.
An example:
public interface Vehicle {}
public class Car implements Vehicle {}
public class MotorBike implements Vehicle {}
public interface VehicleValidator {
void validate();
}
public class CarValidator implements VehicleValidator {
#Override
public void validate() {}
}
public class MotorBikeValidator implements VehicleValidator {
#Override
public void validate() {}
}
public void process(Vehicle vehicle) {
//TODO: validate vehicle
doSomething(vehicle);
}
In Scala I would have done something similar to http://debasishg.blogspot.se/2010/06/scala-implicits-type-classes-here-i.html
But those language constructs is not possible in Java.
This is a classic case for the Double Dispatch design pattern.
You need to add a tiny bit of call-back code in the vehicle, which will be dynamically bound to the appropriate method of the validator at runtime:
public interface Vehicle {
void validate(Validator validator);
}
public class Car implements Vehicle {
public void validate(Validator validator) {
validator.validateCar(this);
}
}
public class MotorBike implements Vehicle {
public void validate(Validator validator) {
validator.validateMotorBike(this);
}
}
public class Validator {
public void validateCar(Car car) {
// validate a car
}
public void validateMotorBike(MotorBike motorBike) {
// validate a motorbike
}
}
public void process(Vehicle vehicle) {
Validator validator = new Validator();
vehicle.validate(validator);
doSomething(vehicle);
}
As Oli Charlesworth wrote in his comment, this is usually done by Visitor pattern. http://en.wikipedia.org/wiki/Visitor_pattern
There is good java example on that wiki page.
Your best bet is a strategy pattern imo, however this won't get you away from doing instanceof/isAssignableFrom checks. However, if you build it well, at least you can abstract it out some, handle it generically, and not have to worry about adding additional checks if you add additional vehicle types.
I could go on to explain strategy patterns, but it's done better here: http://www.javacodegeeks.com/2012/04/strategy-pattern.html (with spring)
Many frameworks will have classes out-of-the-box to facilitate this.
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)
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);
}
}
I'm looking to create a set of functions which all implementations of a certain Interface can be extended to use. My question is whether there's a way to do this without using a proxy or manually extending each implementation of the interface?
My initial idea was to see if it was possible to use generics; using a parameterized type as the super type of my implementation...
public class NewFunctionality<T extends OldFunctionality> extends T {
//...
}
...but this is illegal. I don't exactly know why this is illegal, but it does sort of feel right that it is (probably because T could itself be an interface rather than an implementation).
Are there any other ways to achieve what I'm trying to do?
EDIT One example of something I might want to do is to extend java.util.List... Using my dodgy, illegal syntax:
public class FilterByType<T extends List> extends T {
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
}
You can achieve something like this using a programming pattern known as a 'decorator' (although if the interface is large then unfortunately this is a bit verbose to implement in Java because you need to write single-line implementations of every method in the interface):
public class FilterByType<T> implements List<T> {
private List<T> _list;
public FilterByType(List<T> list) {
this._list = list;
}
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
// Implement List<T> interface:
public boolean add(T element) {
return _list.add(element);
}
public void add(int index, T element) {
_list.add(index, element);
}
// etc...
}
Alternatively, if the methods don't need to access protected members, then static helper methods are a less clucky alternative:
public class FilterUtils {
public static void retainAll(List<T> list, Class<?> c) {
//..
}
public static void removeAll(List<T> list, Class<?> c) {
//..
}
}
What prevents you from just adding new methods to the interface?
If you can't just add the new functionality to old interface, you could consider making another interface and then an implementation which merely implements those two. Just to be clear, in code this is what I mean:
// Old functionality:
public interface Traveling {
void walk();
}
// Old implementation:
public class Person implements Traveling {
void walk() { System.out.println("I'm walking!"); }
}
// New functionality:
public interface FastTraveling {
void run();
void fly();
}
// New implementation, option #1:
public class SuperHero extends Person implements FastTraveling {
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
// New implementation, option #2:
public class SuperHero implements Traveling, FastTraveling {
void walk() { System.out.println("I'm walking!"); }
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
I think it's illegal because you can not guarantee what class T will be. Also there are technical obstacles (parent's class name must be written in bytecode, but Generics information get lost in bytecode).
You can use Decorator pattern like this:
class ListDecorator implements List {
private List decoratingList;
public ListDecorator(List decoratingList){
this.decoratingList = decoratingList;
}
public add(){
decoratingList.add();
}
...
}
class FilterByArrayList extends ListDecorator {
public FilterByAbstractList () {
super(new ArrayList());
}
}
There is a delegation/mixin framework that allows a form of this. You can define a new interface, implement a default implementation of that interface, then request classes which implement that interface but subclass from elsewhere in your hierarchy.
It's called mixins for Java, and there's a webcast right there that demonstrates it.
I'm afraid it's not clear what do you want to get.
Basically, I don't see any benefit in using 'public class NewFunctionality<T extends OldFunctionality> extends T' in comparison with 'public class NewFunctionality extends OldFunctionality' ('public class FilterByType<T extends List> extends T' vs 'public class FilterByType<T> implements List<T>')