I have an interface and I am promised by someone to provide its implementation.
I have to now design a class s.t I can extend "someone's" implementation. However I do not know the name of that implementation.
eg.
interface X{ void methodA(int); int methodB();}
class A implements X { /*impl code here*/}
Now, I don't know , what class is going to implement X. But I want to incorporate those implementations into my code
class B extends <Anyclass that implements interface X>
{/*other impl here*/}
How do I go about doing this? I know in generics you can specify when using Comparator. I want to know if there is anything available for this case?
So you want an instance of X that has the same interface as the class that you get at runtime, but allows you to specify how certain methods of X behave?
If you have an instance of A at runtime, you can use proxy classes to create an object that implements all the interfaces that the class implements, including X, and that overrides some methods of X to do what you want, and delegates the rest to the instance.
Proxy classes are not great efficiency wise and the kind of dynamism they provide is usually easier to achieve by more normal means, so don't overuse them, but where you need a bit of flexible glue at the boundary between two parts of a system, they can really help.
Also note, that the resulting object is not an A, it just implements the same interfaces as A.
Here's your interface:
interface X{ void methodA(int); int methodB();}
Make an abstract super class:
abstract class A implements X { /*impl code here*/}
Now B (and every other class that extends A) promises to implement the interface:
class B extends A {/*other impl here*/}
Is there a reason you want to avoid composition here? You aren't going to have access to the mystery implementation without the name. You can't extend ? extends X, but you can have an instance of it. This is rather trivial using composition:
interface X
{
void methodA( int param );
int methodB();
}
class YourImpl<T extends X> implements X
{
private T delegate;
public YourImpl( T delegate )
{
this.delegate = delegate;
}
void methodA( int param )
{
delegate.methodA( param );
}
int methodB()
{
return delegate.methodB();
}
}
You don't stand to gain much in this example, but if you do additional processing before/after delegation, there's a lot to be gained.
Generally speaking, people gravitate towards inheritance to solve their problems, even when composition is more appropriate. I would suggest reconsidering whether composition is an okay solution for you. Another thing to consider is whether the mystery implementation can use your implementation, rather than vice versa.
I have to now design a class s.t I can extend "someone's" implementation. However I do not know the name of that implementation.
That is not possible. Java does not allow you to extend a generic type parameter. You can only extend a named class.
To achieve what you are trying to achieve, you will need to use some kind of proxying, delegation or wrappering. For example:
public class B implements X {
private X x;
public B(X x) {
this.x = x;
}
// delegate each method in the X interface as required; e.g.
public int someMethod(String s) {
return x.someMethod(s);
}
// add any implementations of B-specific methods.
}
This is not exactly "composition", but I suspect it is the kind of thing you are trying to avoid. Unfortunately (for you), there's no real alternative. The Java language and the JVM both require that every class apart from Object has a single definite super-class.
Related
I have an abstract class that has a concrete method solveand several abstract methods that are used by solve:
public abstract class A{
public void solve(){
//code for solve
}
public abstract void a();
public abstract void b();
}
Then I have another class B that extends A, reimplements the solve methods using the abstract methods from A and new ones added (c,d). It also has a boolean field that indicates if it has to use the solve A or the one from B.
public abstract class B extends A{
boolean useA;
public B(boolean useA){
this.useA = useA
}
public void solve(){
if(useA) super.solve();
else // code for solve
}
public abstract void c();
public abstract void d();
}
Then I have a concrete class C that extends B, implements all methods and has a boolean to indicate if solve has to be used or not.
public class C extends B{
public C(boolean useA){
super(useA);
}
... //code for a,b,c and d
}
Is there any way to do this better? I think that maybe it's not following the principles of OOP.
Some already mentioned the decorator pattern, and there is the strategy pattern too.
However one might use lambdas for injecting some handlers.
Handlers might be done using public service / protected requirement:
class A {
public final f() {
...
onF(x, y);
}
protected abstract void onF(X x, Y y);
}
Solution complexes often are better of without inheritance, but as field, delegating to a field.
In that the answer of #LonelyNeuron gives good arguments.
In short: when in doubt, code it out first, and refactor it to some elegant model. Separating concerns and such.
The problem is, that the best solution for OOP is sometimes heavily over-engineered. So in some cases the solution which takes the least amount of work will be the best.
Also it is really hard to judge in this case. While it is good that you tried to create a Minimal, Complete, and Verifiable example, it lacks the most important information about what should inherit what: the purpose of each class. You could for example imagine that it might make sense to split your class B into two, where one does and the other doesn't override solve(), but if that is a good idea can only be decided to ask the right questions about the purpose of each class.
I suspect that you are asking these questions because you want to know the best way to reuse code in your classes. If that is the case: don't. Taken from this wikipedia article:
In most quarters, class inheritance for the sole purpose of code reuse has fallen out of favor. The primary concern is that implementation inheritance does not provide any assurance of polymorphic substitutability—an instance of the reusing class cannot necessarily be substituted for an instance of the inherited class. An alternative technique, explicit delegation, requires more programming effort, but avoids the substitutability issue. In C++ private inheritance can be used as a form of implementation inheritance without substitutability. Whereas public inheritance represents an "is-a" relationship and delegation represents a "has-a" relationship, private (and protected) inheritance can be thought of as an "is implemented in terms of" relationship.
Suppose, I have 2 configurations.
First one:
interface I {
...
}
class A implements I {
...
}
class B implements I {
...
}
class Component {
I i;
Component (I i) {
this.i = i;
}
}
Second one:
class C {
...
}
class A extends C {
...
}
class B extends C {
...
}
class Component {
C c;
Component (C c) {
this.c = c;
}
}
What in the difference between those two configurations which are using two different loose coupling mechanisms (based on interface and based on class)?
Why should I need to use interface over class?
Mainly, using classes is a more heavy approach. Base classes usually contain concrete (non-abstract) methods. And if you derive from them you will need also to inherit such concrete methods, which you may not want.
For example, imagine that you want to benefit from composition design patterns like the decorator pattern. Here, your decorator needs also to derive from the base class and will inherit the concrete methods. However, your decorator will not need the concrete method to function.
In summary, it is more hard/unclean to do object composition if your abstractions are class-based.
Abstraction through interfaces on the other hand, does not force implementing classes to inherit any concrete method implementation. Therefore, it is more clean.
An object can implements multiple interfaces but can only extends one class, so sometimes the user of your loose coupled library may not be able to extends your class.
when you extends, you incorporate the code of the superclass into yours, sometimes there is no code to incorporate so implements is better suited.
Finally it is not the same paradigm, when you write "B extends A" you say "I am A, I do the same things, but I can also make other things". When you write "B implements A" you say "I am B, but you can treat me as an A".
Long story short, the only practical reason would be the first.
A hierarchy based upon interfaces is a good desing approach, because it eases implementation: You can always implement an interface, but not always you can extend a class (for example, a final class). Or, in the other hand, not always a class' author want it to be extended.
So, you are highly interested on using interfaces over classes, because in this way you may accept a wider set of implementations. For example:
Using classes:
class Component
{
AbstractList c;
Component (AbstractList c){...}
}
... Component would accept ArrayList or Vector.
Instead, using interfaces:
class Component
{
List c;
Component (List c){...}
}
... Component would be able to accept ArrayList, Vector, CopyOnWriteArrayList...
I was thinking about programming to interfaces and not to concrete classes, but I had a doubt: should any interface method be able to hold references to concrete classes?
Suppose the following scenarios:
1)
public interface AbsType1 {
public boolean method1(int a); // it's ok, only primitive types here
}
2)
public interface AbsType2 {
public boolean method2(MyClass a); // I think I have some coupling here
}
Should I choose a different design here in order to avoid the latter? e.g.
public interface MyInterface {} // yes, this is empty
public classe MyClass implements MyInterface {
// basically identical to the previous "MyClass"
}
public interface AbsType2 {
public boolean method2(MyInterface a); // this is better (as long as the
// interface is really stable)
}
But there's still something that doesn't convince me... I feel uncomfortable with declaring an empty interface, though I saw someone else doing so.
Maybe and Abstract Class would work better here?
I am a little bit confused.
EDIT:
Ok, I'll try to be more specific by making an example. Let's say I'm desining a ShopCart and I want of course to add items to the cart:
public interface ShopCart {
public void addArticle(Article a);
}
Now, if Article were a concrete class, what if its implementation changes over time? This is why I could think of making it an Interface, but then again, it's probably not suitable at least at a semantic level because interfaces should specify behaviours and an Article has none (or almost none... I guess it's a sort of entity class).
So, probably I'm ending up right now to the conclusion that making Article an abstract class in this case would be the best thing... what do you think about it?
I would use interfaces because composition is much better than inheritance. "Should any interface method be able to hold references to concrete classes ?", why it shouldn't? Some classes within package are coupled, it's a fact and common use technique. When you marked this relation in interface then you see on which classes is dependent your implementation. Dependency or composition relations are not inheritance so a i would avoid abstract class.
In my opinion Interfaces are fine for all types where the implementation may vary. But if you define a module which introduces a new type, that isn't intended to have alternative implementations then there is no need to define it as an Interface in the first place. Often this would be over-design in my opinion. It depends on the problem domain and often on the way how support testing or AOP-weaving.
For example consider a 2D problem domain where you need to model a Location as a type. If it is clear that a Location is always represented by a x and y coordinate, you may provide it as a Class. But if you do not know which properties a Location could have (GPS data, x, y, z coordinates, etc.) but you rely on some behavior like distance(), you should model it as an Interface instead.
If there are no public methods which AbsType would access in MyClass then the empty interface is probably not a good way to go.
There is no interface declaration (contract) for static methods, which otherwise might make sense here.
So, if AbsType is not going to use any methods from MyClass/MyInterface, then I assume it's basically only storing the class object for some other purpose. In this case, consider using generics to make clear how you want AbsType to be used without coupling closely to the client's code, like
public class AbsType3<C extends Class<?>> {
public boolean method3(T classType) {...}
}
Then you can restrict the types of classes to allow if needed by exchanging the <C extends Class<?>> type parameter for something else which may also be an interface, like
<C extends Class<Collection<?>>>.
Empty interfaces are somewhat like boolean flags for classes: Either a class implements the interface (true) or it doesn't (false). If at all, these marker interfaces should be used to convey an significant statement about how a class is meant to be (or not to be) used, see Serializable for example.
I want to create a class that does not implement any method of an interface, but extends any implementation of A with it's own methods.
Let's assume we have the following:
public interface A {
public void a();
}
and
public class B implements A {
#override
public void a() {
System.out.println("a");
}
}
I now want to create a class C that also implements A and takes another random implementation of A:
public class C implements A {
public C(A a) {
//what do I need to do with a here?
}
public void c() {
System.out.println("c");
}
}
Now if I have the following:
A b = new B();
A c = new C(b);
c.a();
The output should be "a".
I can't just
public class C extends B {
...
as C is supposed to be able to work with any implementation of A, not just B.
I also can't
public class C implements A {
private a;
public C(A a) {
this.a = a;
}
#override
public void a() {
a.a();
}
public void c() {
System.out.println("c");
}
}
since that would mean that I have to redirect every single interface method and rewrite C whenever something changes with A.
Is there any way to handle that problem in Java?
For another example, replace A: List; B: ArrayList; C: FooList; a(): size()
What you're looking for is a dynamic proxy, which automatically implements all the methods of an interface by delegating to a concrete implementation of this interface. That's not trivial, but not so complex to do either, using Java's Proxy class.
A concrete example of such a proxy, which "adds" methods to any instance of PreparedStatement by wrapping it, can be found at https://github.com/Ninja-Squad/ninja-core/blob/master/src/main/java/com/ninja_squad/core/jdbc/PreparedStatements.java
Unfortunately, there's no way to do it in Java, other than your last code snippet. Various IDEs will help you with the code generation, though, and marking all methods #override will mean that you'll get a warning or an error if your implementation of C doesn't exactly match A's interface.
For Eclipse (and, apparently, IntelliJ), see the "Generate Delegate Methods" command.
This is probably not going to immediately help you, but if you used Java 8, you could solve this with defender methods, which are methods implemented in the interface.
You would then, for each existing implementation class, add your own class which extends the class and implements your additional interface with the defender methods. The methods would be "mixed into" your class.
Java 8 is just around the corner, though, so it is not a far-off solution. Oracle has promised it will release it by the end of this quarter, meaning in less than a month and a half at the latest.
Is there any way to handle that problem in Java?
Basically, no.
What you are describing a wrapper class that delegates calls to the wrapped method. The only way you can implement that (in regular Java) is to implement all of the methods and have them make the calls.
Another alternative would be to use the Proxy class ... which will effectively generate a dynamic proxy. The problem is that this requires an InvocationHandler that will (I guess) use reflection to make the call to the wrapped object. It is complicated and won't be efficient.
If your goal is simply to avoid writing code, I think this is a bad idea. If your goal is to writing the same code over and over (e.g. because you have lots of exampled of C for a given A), then consider coding an abstract class for the C classes that deals with the wrappering / delegation.
It would also be possible to generate the wrapper class C from nothing, using the BCEL library or similar. But that's an even worse idea (IMO).
I have a structure like follows
Interface A
Interface B extends Interface A
abstract Class C implements Interface B
now concrete Class D extends Class C
Now I am using Interface B in a different class and returning the concrete class D object.
Interface B contains getters and setters and modifying methods.
What I want is that I want to take out all the getters from Interface B somehow and put them in a separate interface so that when I return a concrete object I don't have access to the setters and modifiers of Interface B. But I want to use Interface B as my return object with this newly built read-only concrete object. I am not get any idea about how to achieve this?
One way to achieve this would be to create a read-only wrapper object which implements interface B, propagates the getters to the wrapped object and raises an exception (like IllegalAccessEXception or InvalidStateException) from within the setters and modifiers.
It sounds like you are referring to the Proxy design pattern : http://en.wikipedia.org/wiki/Proxy_pattern.
In your case, you want Interface B to support getting/setting of certain fields, but you want it to provide a specific proxy for setting and getting those fields, rather then directly editing them.
This is rarely done, but you can create an inner-interface, which is specific and local to the interface you want to support. For example :
public interface Proxiable {
public static interface Proxy
{
}
public ProxySub getProxy();
}
Thus, your interface is defining a proxy interface - and anyone who extends your interface will have to provision a Proxy provider.
However, unless you have a REALLY good reason for doing this, you might be overabstracting. Interfaces are generic enough that it is usually sufficient to leave the details of HOW methods are implemented to subclasses, rather than forcing this superstructure at the interface level.
Elaborating on the excellent suggestion by #rsp :
Create a "read-only" interface
public interface MyInterfaceRO {
public int getFoo();
public String getBar();
// etc...
}
Create the "read-write" interface, corresponding to your B
public interface MyInterfaceRW extends MyInterfaceRO {
public void setFoo(int foo);
public void setBar(String bar);
// ...
}
IMO, the simplest way to do what you want (prevent modification) is to just return MyInterfaceRO. The caller (unless they do a cast) will have no ability to call setFoo(), in fact, in their IDE they won't even see .setFoo() as an option.
I don't understand why you really want to return a type B (my RW above), but, if you do, you are stuck with the caller having the ability to see and call setFoo(). Probably your best bet would be to follow the precedent set in java's Collections and throw an UnsupportedOperationException. As a convenience, you could offer a method
public boolean isModifiable();
but you can't force the caller to use and respect that.