I have the following probem.
I have these Java classes:
class A {
B makeB() {
return new B();
}
}
class B implements X {
// X methods implementations (plus other methods)
}
interface X {
// methods declarations
}
For testing purposes, I need to modify the method makeB
so that it can create a new instance of every class that implements the X interface.
I tried with generics:
class A<T extends X> {
X makeB() {
return new T();
}
}
but this code isn't correct. I also tried in the following way:
class A {
X makeB() {
return X.createInstance();
}
}
class B implements X {
@Override
public static X createInstance() {
return new B();
}
// X methods implementations (plus other methods)
}
interface X {
static X createInstance() {}
// other methods declarations
}
but Java doesn't support overriding of static methods.
How can I change makeB
so that it behaves as I want (if there is a way to do so)?
(Neither the title neither the description of my question are very clear, the problem is that I can't find a way to say it better. My apologies.)
Thanks to everyone who will answer.