I've a parameterized interface:
public interface MyInterface<T> {
void run(T e);
}
And classes implementing the interface:
public class MyClass1 implements MyInterface<SomeOtherClass1> {
public void run(SomeOtherClass1 e) {
// do some stuff with e
}
}
public class MyClass2 implements MyInterface<SomeOtherClass2> {
public void run(SomeOtherClass2 e) {
// do some stuff with e
}
}
The number of different MyClass*X* is known and exhaustive, and there is only one instance of each MyClass*X*, so I would like to use an enum:
public enum MyEnum {
MY_CLASS_1,
MY_CLASS_2;
}
To be able to use MyEnum.MY_CLASS_1.run(someOtherClass1); for example (I would then have every instance of MyInterface in one same place). Is it even possible (and if yes, how)? Because I'm quite stuck for now...
What I tried yet:
public enum MyEnum {
MY_CLASS_1(new MyClass1()),
MY_CLASS_2(new MyClass2());
private MyInterface<?> instance;
private MyEnum(MyInterface<?> instance) {
this.instance = instance;
}
public void run(/* WhichType? */ e) {
instance.run(e);
}
}
In the above method, when using the type Object for the e parameter:
public void run(Object e) {
instance.run(e);
// ^^^
// The method run(capture#3-of ?) in the type MyInterface<capture#3-of ?> is not applicable for the arguments (Object)
}
The problem I think is with that private MyInterface<?> instance field: I need to know how is the instance parameterized, using something like private MyInterface<T> instance, but I can't find a working solution...
In short, I'm stuck ;)
PS: since the run methods bodies can be quite long, I'm trying to avoid anonymous classes within the enum:
public enum MyEnum {
MY_CLASS_1 {
/* any method, etc. */
},
MY_CLASS_2 {
/* any method, etc. */
},
}
MyEnum would then become totally unreadable.
It's not possible. That's one of the enum limitations I find most annoying, but all you can do is try to work around it (as you would have done in Java pre-5.0).
Only the enum itself can implement the interface and the generics must be specified at the enum level, so only Object or some common interface for those two would apply in your case.
Declaring any aspect that you want to treat polymorphically (the run() method, in your example) inside the enum itself (and overriding the behavior in each constant) is usually the best workaround. Of course, you need to loosen up your type safety requirements.
If you want to keep those strategies separated, you still need a run(Object) method inside the enum and that will be defined in each constant with some explicit cast, since you simply cannot have different method signatures per enum instance (or even if you can, they won't be visible as such from the outside).
A hint on how to trick the compiler, if you really want to do that rather than a redesign or explicit casts for each instance:
enum MyEnum implements MyInterface<Object> {
MY_CLASS_1(new MyClass1()),
MY_CLASS_2(new MyClass2());
// you may also drop generics entirely: MyInterface delegate
// and you won't need that cast in the constructor any more
private final MyInterface<Object> delegate;
MyEnum(MyInterface<?> delegate) {
this.delegate = (MyInterface<Object>) delegate;
}
#Override
public void run(Object e) {
delegate.run(e);
}
}
The above will work and you'll get a ClassCastException (as expected) if you try to use MyEnum.MY_CLASS_1.run() with something other than SomeOtherClass1.
As Costi points out, enums themselves can't be generic. However I think I can identify where you went wrong in your design:
There is only one instance of each MyClassX, so I would like to use
an enum:
public enum MyEnum {
MY_CLASS_1,
MY_CLASS_2;
}
You're saying that each of these classes is a singleton. So they should in fact each be an enum:
public enum MyClass1 implements MyInterface<SomeOtherClass1> {
INSTANCE;
#Override
public void run(SomeOtherClass1 e) {
// do some stuff with e
}
}
public enum MyClass2 implements MyInterface<SomeOtherClass2> {
INSTANCE;
#Override
public void run(SomeOtherClass2 e) {
// do some stuff with e
}
}
This makes more sense because if you think about it, you don't need to enumerate these two implementations, so there's no need for them to live together. It's enough to use Josh Bloch's enum pattern for each of them individually.
Related
I do have a service which needs to handle two types of meal.
#Service
class MealService {
private final List<MealStrategy> strategies;
MealService(…) {
this.strategies = strategies;
}
void handle() {
var foo = …;
var bar = …;
strategies.forEach(s -> s.remove(foo, bar));
}
}
There are two strategies, ‘BurgerStrategy’ and ‘PastaStrategy’. Both implements Strategy interface with one method called remove which takes two parameters.
BurgerStrategy class retrieves meals of enum type burger from the database and iterate over them and perform some operations. Similar stuff does the PastaStrategy.
The question is, does it make sense to call it Strategy and implement it this way or not?
Also, how to handle duplications of the code in those two services, let’s say both share the same private methods. Does it make sense to create a Helper class or something?
does it make sense to call it Strategy and implement it this way or not
I think these classes ‘BurgerStrategy’ and ‘PastaStrategy’ have common behaviour. Strategy pattern is used when you want to inject one strategy and use it. However, you are iterating through all behaviors. You did not set behaviour by getting one strategy and stick with it. So, in my honour opinion, I think it is better to avoid Strategy word here.
So strategy pattern would look like this. I am sorry, I am not Java guy. Let me show via C#. But I've provided comments of how code could look in Java.
This is our abstraction of strategy:
public interface ISoundBehaviour
{
void Make();
}
and its concrete implementation:
public class DogSound : ISoundBehaviour // implements in Java
{
public void Make()
{
Console.WriteLine("Woof");
}
}
public class CatSound : ISoundBehaviour
{
public void Make()
{
Console.WriteLine("Meow");
}
}
And then we stick with one behaviour that can also be replaced:
public class Dog
{
ISoundBehaviour _soundBehaviour;
public Dog(ISoundBehaviour soundBehaviour)
{
_soundBehaviour = soundBehaviour;
}
public void Bark()
{
_soundBehaviour.Make();
}
public void SetAnotherSound(ISoundBehaviour anotherSoundBehaviour)
{
_soundBehaviour = anotherSoundBehaviour;
}
}
how to handle duplications of the code in those two services, let’s say both share the same private methods.
You can create one base, abstract class. So basic idea is to put common logic into some base common class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete case. Let me show an example.
An abstract class which has common behaviour:
public abstract class BaseMeal
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{
// put here code that can be shared among subclasses to avoid code duplication
}
public abstract void UnCommonBehaviourShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class BurgerSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class PastaSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
I want to create a wrapper class over another class so that it hides the functionality of wrapped class and also the wrapper provides certain methods of its own.
For example, lets say we have class A as
public class A{
void method1(){ ... do something ... }
void method2(){ ... do something ... }
void method3(){ ... do something ... }
}
Now I want another class B which wraps class A, so that it has its own methods, and also if someone asks method of class A, it should delegate it to class A.
public class B{
// if someone asks method1() or method2() or method3() ... it should delegate it to A
// and also it has own methods
void method4(){ ... do something ... }
void method5(){ ... do something ... }
}
I can't use inheritance (i.e B extends A) because its not easy with my use case (where A has concrete constructor with some parameters which we can't get ... but we can get the object of A).
I can't simply delegate each function in A using object of A (because there are several functions in A)
Is there any other way to obtain class B with said restrictions?
Important Note: Class A is handled by someone else. We can't change any part of it.
What you have described is a Decorator pattern coined by GOF. There is plenty of sources on the Internet about it. It is similar to the Proxy pattern (as in the answer of Pavel Polivka) but the intent is different. You need the Decorator pattern:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. sourcemaking.com
As you have written in a comment
class A inherits from single interface containing several methods
I assume A implements AIntf and contains all the methods you want.
public class BDecorator implements AIntf {
private A delegate;
private BDecorator(A delegate) {
this.delegate = delegate;
}
void method1(){ delegate.method1(); }
// ...
void method4(){ /* something new */ }
There are several functions in A, and I don't want to do tedious work of writing each method explicitly in B.
Java is a verbose language. However, you don't need to do this by hand, every decent IDE provides automatic generation of delegate methods. So it will take you 5 seconds for any amount of methods.
The class A is not in my control, I mean someone might update its method signatures, In that case I need to watch over class A and made changes to my class B.
If you create B you are responsible for it. You at least notice if anything changed. And once again, you can re-generate the changed method with the help of an IDE in an instant.
This can be easily done with CGLIB but will require few modifications. Consider if those modifications may not be harder to do that the actual delegation of the methods.
You need to extend the classes, this can be done by adding the no arg constructor to class A, we will still delegate all the methods so do not worry about unreachable params, we are not worried about missing data, we just want the methods
You need to have CGLIB on you classpath cglib maven, maybe you already have it
Than
A would look like
public class A {
private String arg = "test";
public A() {
// noop just for extension
}
public A(String arg) {
this.arg = arg;
}
public void method1() {
System.out.println(arg);
}
}
B would look like
public class B extends A implements MethodInterceptor {
private A delegate;
private B(A delegate) {
this.delegate = delegate;
}
public static B createProxy(A obj) {
Enhancer e = new Enhancer();
e.setSuperclass(obj.getClass());
e.setCallback(new B(obj));
B proxifiedObj = (B) e.create();
return proxifiedObj;
}
void method2() {
System.out.println("a");
}
#Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
Method m = findMethod(this.getClass(), method);
if (m != null) { return m.invoke(this, objects); }
Object res = method.invoke(delegate, objects);
return res;
}
private Method findMethod(Class<?> clazz, Method method) throws Throwable {
try {
return clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
} catch (NoSuchMethodException e) {
return null;
}
}
}
That you can do
MyInterface b = B.createProxy(new A("delegated"));
b.method1(); // will print delegated
This is not very nice solution and you probably do not need it, please consider refactoring your code before doing this. This should be used only in very specific cases.
There are several (5+) classes, in code I cannot change, that I need to extend by a few fields. Is there any way to do this without writing (and editing every time I need to change something) the almost exactly same code 5 times? So is there any more elegant way than this:
class Subclass1 extends Superclass1 {
private String newField;
public String getNewField() {
return newField;
}
public void setNewField(String newField) {
this.newField = newField;
}
}
class Subclass2 extends Superclass2 {
private String newField;
public String getNewField() {
return newField;
}
public void setNewField(String newField) {
this.newField = newField;
}
}
//...
I do NOT want multiple inheritance, I want 5 seperate subclasses - just without the duplicate code, because the subclasses all add exactly the same.
The only alternative I can think of is copying the original classes and having the copy extend a Superclass which is probably even worse.
No, you can't do this in Java. You can in certain other JVM-based languages, such as Scala (traits). However, if you must use plain Java, you might consider the following:
Determine the (hopefully single) purpose of the fields you are adding, and the behavior that you want.
Create a new class encompassing all of the fields and the new methods. For example:
public class ExtraFields // Don't use this name!
{
private String myExtraField1;
private String myExtraField2;
// etc.
public void doSomethingWithExtraFields() {
// etc.
}
}
Then, you could take one of the following approaches:
Subclass each of the five classes, and add one field, which is an instance of the class you created above, and delegate behavior accordingly. You will have to use this approach if you must have the extra fields in places where you must pass in one of your five classes. For example:
public class Subclass1 extends Superclass1
{
private ExtraFields extraFields;
public MySubclass()
{
super();
extraFields = new ExtraFields();
}
public void doSomethingWithExtraFields()
{
extraFields.doSomethingWithExtraFields();
}
}
Create a new wrapper class that contains an instance of both your new class created above, and one of those five subclasses. You can make this typesafe using generics. For example:
public class Wrapper<T> // Don't use this name either...
{
private ExtraFields extraFields;
private T myClass;
public Wrapper(T myClass) {
this.myClass = myClass;
this.extraFields = new ExtraFields();
}
}
In this second approach, you don't strictly need the ExtraFields class. But it's still often a good idea to do this so as to encapsulate related functionality.
Hope that helps!
Since you can't change the base classes, it's impossible to eliminate the redundancy. Eric Galluzzo's idea to store the extra fields in a separate class is the best one so far, but I don't know if that's practical in your case. If it isn't, create an interface that defines the extra fields. You'll still have to do a lot of repetitive typing, but at least you'll know immediately when you've made a mistake.
You could use a generic wrapper class, as long as it wouldn't be too tedious to change the rest of the code that works with it.
class Wrapper<E> {
private E obj;
private String newField;
public Wrapper (E obj) {
this.obj = obj;
}
public E get() {
return obj;
}
public String getNewField() {
return newField;
}
public void setNewField(String newField) {
this.newField = newField;
}
}
Is there a way to define a method in an interface where implementations can be typed to the implementing class? Here's a concrete example of my initial attempt to solve it, but I'll point out where it fails.
public interface ErrorMeasurable<T extends ErrorMeasurable<T>> {
// I want every implementation of this method to accept
// the implementing type as a parameter. I'm willing to accept
// that programmers can maliciously type it to something else
// that meets the type boundary. I'm not willing to accept
// polymorphic usage to be verbose or strange as the below example shows.
boolean approxEquals(T that);
}
// This works...
public class MyDecimal implements ErrorMeasurable<MyDecimal> {
boolean approxEquals(MyDecimal that) { ... }
}
// But polymorphism doesn't work well...
public interface MyNumber<T extends ErrorMeasurable<T>> implements ErrorMeasurable<T> {
boolean approxEquals(T that) { ... }
}
public class MyDecimal2 implements MyNumber<MyDecimal> {
boolean approxEquals(MyDecimal that) { ... }
}
public class UsesNumbers {
// PROBLEM 1: the type parameter is unbound.
MyNumber rawNumber1, rawNumber2;
// PROBLEM 2: This binds the type parameter but it is hard to understand why its typed to itself
MyNumber<MyNumber> boundNumber1, boundNumber2;
void example() {
// PROBLEM 3: There will be a compiler warning about the raw types.
rawNumber1.approxEquals(rawNumber2);
// Works without warnings, see PROBLEM 2 though.
boundNumber1.approxEquals(boundNumber2);
}
}
I don't think what you want can be done with the current level of generics in Java.
You cannot do anything about stopping others using generics as raw types, but that will at least issue a warning. If there aren't warnings, code is guaranteed to be typesafe.
For problem #2, what you probably want is:
public interface MyNumber<T extends MyNumber<T>> implements ErrorMeasurable<T> {
boolean approxEquals(T that) { ... }
}
public class MyDecimal2 implements MyNumber<MyDecimal2> {
boolean approxEquals(MyDecimal2 that) { ... }
}
public class MyDecimal3 extends MyDecimal2 {
boolean approxEquals(MyDecimal2 that) { ... }
}
public class UsesNumbersClass<T extends MyNumber<T>> {
T boundNumber1, boundNumber2;
void example() {
boundNumber1.approxEquals(boundNumber2);
}
}
public class UsesNumbersOnlyMethod {
<T extends MyNumber<T>> void example(T boundNumber1, T boundNumber2) {
boundNumber1.approxEquals(boundNumber2);
}
}
Every class can have only single actual implementation of method boolean approxEquals(T that), so you have to decide for each class if you want that method to represent exactly that class (like MyDecimal2), or you want it to be able to handle broader types - some parent type (like MyDecimal3). Almost always you would want it to handle exactly that class.
Is it possible to create an inner class within an interface?
If it is possible why would we want to create an inner class like that since
we are not going to create any interface objects?
Do these inner classes help in any development process?
Yes, we can have classes inside interfaces. One example of usage could be
public interface Input
{
public static class KeyEvent {
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 1;
public int type;
public int keyCode;
public char keyChar;
}
public static class TouchEvent {
public static final int TOUCH_DOWN = 0;
public static final int TOUCH_UP = 1;
public static final int TOUCH_DRAGGED = 2;
public int type;
public int x, y;
public int pointer;
}
public boolean isKeyPressed(int keyCode);
public boolean isTouchDown(int pointer);
public int getTouchX(int pointer);
public int getTouchY(int pointer);
public float getAccelX();
public float getAccelY();
public float getAccelZ();
public List<KeyEvent> getKeyEvents();
public List<TouchEvent> getTouchEvents();
}
Here the code has two nested classes which are for encapsulating information about event objects which are later used in method definitions like getKeyEvents(). Having them inside the Input interface improves cohesion.
Yes, you can create both a nested class or an inner class inside a Java interface (note that contrarily to popular belief there's no such thing as an "static inner class": this simply makes no sense, there's nothing "inner" and no "outter" class when a nested class is static, so it cannot be "static inner").
Anyway, the following compiles fine:
public interface A {
class B {
}
}
I've seen it used to put some kind of "contract checker" directly in the interface definition (well, in the class nested in the interface, that can have static methods, contrarily to the interface itself, which can't). Looking like this if I recall correctly.
public interface A {
static class B {
public static boolean verifyState( A a ) {
return (true if object implementing class A looks to be in a valid state)
}
}
}
Note that I'm not commenting on the usefulness of such a thing, I'm simply answering your question: it can be done and this is one kind of use I've seen made of it.
Now I won't comment on the usefulness of such a construct and from I've seen: I've seen it, but it's not a very common construct.
200KLOC codebase here where this happens exactly zero time (but then we've got a lot of other things that we consider bad practices that happen exactly zero time too that other people would find perfectly normal so...).
A valid use, IMHO, is defining objects that are received or returned by the enclosing interface methods. Tipically data holding structures. In that way, if the object is only used for that interface, you have things in a more cohesive way.
By example:
interface UserChecker {
Ticket validateUser(Credentials credentials);
class Credentials {
// user and password
}
class Ticket {
// some obscure implementation
}
}
But anyway... it's only a matter of taste.
Quote from the Java 7 spec:
Interfaces may contain member type declarations (§8.5).
A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.
It is NOT possible to declare non-static classes inside a Java interface, which makes sense to me.
An interesting use case is to provide sort of a default implementation to interface methods through an inner class as described here: https://stackoverflow.com/a/3442218/454667 (to overcome the problem of single-class-inheritance).
Yes it is possible to have static class definitions inside an interface, but maybe the most useful aspect of this feature is when using enum types (which are special kind of static classes). For example you can have something like this:
public interface User {
public enum Role {
ADMIN("administrator"),
EDITOR("editor"),
VANILLA("regular user");
private String description;
private Role(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public String getName();
public void setName(String name);
public Role getRole();
public void setRole(Role role);
...
}
It certainly is possible, and one case where I've found it useful is when an interface has to throw custom exceptions. You the keep the exceptions with their associated interface, which I think is often neater than littering your source tree with heaps of trivial exception files.
interface MyInterface {
public static class MyInterfaceException extends Exception {
}
void doSomething() throws MyInterfaceException;
}
What #Bachi mentions is similar to traits in Scala and are actually implemented using a nested class inside an interface. This can be simulated in Java. See also java traits or mixins pattern?
Maybe when you want more complex constructions like some different implementation behaviours, consider:
public interface A {
public void foo();
public static class B implements A {
#Override
public void foo() {
System.out.println("B foo");
}
}
}
This is your interface and this will be the implementee:
public class C implements A {
#Override
public void foo() {
A.B b = new A.B();
b.foo();
}
public static void main(String[] strings) {
C c = new C();
c.foo();
}
}
May provide some static implementations, but won't that be confusing, I don't know.
I found a use fir this type of construct.
You can use this construct to defines and group all the static final constants.
Since, it is an interface you can implement this on an class.
You have access to all the constants grouped; name of the class acts as a namespace in this case.
You can also create "Helper" static classes for common functionality for the objects that implement this interface:
public interface A {
static class Helper {
public static void commonlyUsedMethod( A a ) {
...
}
}
}
I'm needing one right now. I have an interface where it would be convenient to return a unique class from several of it's methods. This class only makes sense
as a container for responses from methods of this interface.
Hence, it would be convenient to have a static nested class definition, which is associated only with this interface, since this interface should be the only place where this results container class is ever created.
For instance traits (smth like interface with implemented methods) in Groovy. They are compiled to an interface which contains inner class where all methods are implemented.