Suppose I have three isolated public classes (no IS-A relationship) A, B and C. I want to define a field in C such that it\'s type can either be A or B.
Currently I\'m a
You can't do that but you can set boundaries on what type you want to accept.
If you have
class A extends BaseType {}
class B extends BaseType {}
you can define the class C
to be
class C<T extends BaseType> { ... }
Either a class
or an interface
as base type work.
Make the constructor private:
private C(T param){
And then provide static factory methods to create instances of particular types:
public static <T extends A> C<T> create(T param) {
return new C<>(param);
}
public static <T extends B> C<T> create(T param) {
return new C<>(param);
}
This doesn't prevent you from using the type C<SomeOtherType>
; you just can't create an instance of it.
You could use a marker interface for that:
interface AllowedInC {
// intentionally empty because it will be used as a mere marker
}
class A implements AllowedInC {
...
}
class B implements AllowedInC {
...
}
class C<T extends AllowedInC> {
...
}
Only classes A or B (or another class implementing AllowedInC
) will be useable in C<T>
.