While sub classing from generic class type/Formal type parameter T/E
with valid class type/Actual type parameter say eg Type/String
there are many combinations occurs and that confusing which one to use and when?
public class SubClass<T> implements SuperIfc<T> <-- It is straight forward to understand
public class SubClass<T> implements SuperIfc<Type>
public class SubClass<Type> implements SuperIfc<T>
public class SubClass<Type> implements SuperIfc<Type>
public class SubClass<Type> implements SuperIfc
public class SubClass implements SuperIfc<Type>
public class SubClass implements SuperIfc<T> <--- Hope we cannot declare <T> in his case while initialising SubClass.
// Bounded type parameter
public class SubClass<T extends Type> implements SuperIfc<Type>
public class SubClass<T extends Type> implements SuperIfc<T> <-- Looks <T> at SuperIfc also refers <T extends Type>, and no need to declare it again at SuperIfc.
// Recursive type bound
public class SubClass<T extends Comparable<T>>> implements SuperIfc<T>
public class SubClass<T extends Comparable<T>>> implements SuperIfc<Type>
So that i can be more clearer on solving incompatible types while subclassing
Case_1:
public class Test {
interface TestIfc {
public static <T extends TestIfc> T of(int choice) {
if(choice == 1) {
return new TestImpl(); <-- PROB_1: incompatible type error
} else {
return new SomeOtherTestImpl(); //incompatible type error
}
}
}
static class TestImpl implements TestIfc {}
static class SomeOtherTestImpl<T extends TestIfc> implements TestIfc {
//The below method also having same error though with declaration
public T of() {
return new TestImpl(); <-- PROB_2: incompatible type error
}
}
}
Case_1: PROB_1: return type is T extends TestIfc
and returned TestImpl implements TestIf
So what is wrong?
Case_1: PROB_2: Similar to PROB_1, how to rectify without external casting. Please help.
Case_2:
public interface SuperIfc<T> {
public T create(Object label);
}
class Type {
public static Type of(){
return new Type();
}
}
------
public class SubClass<Type> implements SuperIfc<Type>{
@Override
public Type create() {
return Type.of(); <---- PROB_1: cannot resolve method
}
}
-------
public class SubClass<T extends Type> implements SuperIfc<Type>{
@Override
public Type create() {
return Type.of(); <---- PROB_1: is resolved
}
}
SuperIfc<Type> object = new SubClass(); <-- PROB_2 Unchecked assignement warning
SuperIfc<Type> object = new SubClass<TypeImpl>(); <-- PROB_3: bound should extend Type
I would like to know how to resolve Case_2, PROB_1 and PROB_2 together?
How to write subclass for generic super class with class types and what are the rules?
What should be taken care when changing generic T
to class Type
while subclassing? may be the difference between below and when to use?
public class SubClass<Type> implements SuperIfc<Type> public class SubClass<Type> implements SuperIfc public class SubClass implements SuperIfc<Type> public class SubClass<T extends Type> implements SuperIfc<Type> public class SubClass<T extends Type> implements SuperIfc<T> public class SubClass<T> implements SuperIfc<Type>
In the first of()
method, the method can return any type that implements InformationIfc
, but your method always returns a specific implementation - InformationImpl
- which is not acceptable.
For example, if you had some other class SomeOtherInformationImpl
that implements that interface, the caller of that method would be allowed to write:
SomeOtherInformationImpl i = InformationImpl.of();
but your method doesn't return a SomeOtherInformationImpl
.
The second of()
method has the same issue as the first method. If you instantiated your class with:
InformationImpl i = new InformationImpl<SomeOtherInformationImpl>();
the of()
method would have to return a SomeOtherInformationImpl
, not a InformationImpl
.
Problems with case one.
PROB_1: return type is T extends TestIfc
Why do you have a generic here at all?. Since you have a static method I can do.
TestIfc broken = TestIfc<SomeOtherImplementation>.of(0);
SomeOtherImplementation
is not a TestImpl
. This is broken by design. What you really want is.
public static TestIfc of(int choice)
Next.
static class SomeOtherTestImpl<T extends TestIfc> implements TestIfc {
TestIfc
is not parameterized, SomeOtherTestImp
is, but it is completely unrelated to the interface you're implementing. Not to mention, TestIfc has a static method of
that has nothing to do with the interface.
If I had to guess, I would think you want.
interface TestIfc<T>{}
static class TestImpl implements TestIfc<TestImpl> {}
static class SomeOtherTestImpl<T extends TestIfc> implements TestIfc<T>{}
That is the best I could come up with, because it is unclear what you actually want to happen.
Your examples for question 3
public class SubClass<Type> implements SuperIfc<Type>
This is broken, because SubClass<Type>
declares Type
to be the name of a generic parameter. It puts no restriction on the type, hence you get the method not found error.
public class SubClass<Type> implements SuperIfc
Broken, makes a generic parameter named Type
, has nothing to do with your raw type version of SuperIfc
public SubClass implements SuperIfc<Type>
This is good.
public class SubClass<T extends Type> implements SuperIfc<Type>
public class SubClass<T> implements SuperIfc<Type>
These are both good, but the T has no relation to the SuperIfc parameter, hence your implementation would be.
public Type create(Object label);
The first generic parameter says the name you're going to use through the class.
This is a long answer, but please read through it (at least case 1 and the very end, you can skip over problem 2's solution in case 2 if you wish)
Your problem here is that the compiler cannot prove that T
is the same as TestImpl
or SomeOtherTestImpl
. What if there was another class, call it TestFoo
, that implemented TestIfc
? Then, if you called the method as TestIfc.<TestFoo>of(1)
, you would expect an object of type TestFoo
, but you would instead get a TestImpl
, which is wrong. The compiler doesn't want you doing that, so it throws an error. What you should do is just remove the generics, like so:
public static TestImpl of(int choice) {
if(choice == 1) {
return new TestImpl();
} else {
return new SomeOtherTestImpl();
}
}
And then you can safely call TestIfc.of
.
This is basically the same thing. The compiler can't prove that the type parameter T
of SomeOtherTestImpl
is the same as TestImpl
. What if you have an object like this (where TestFoo
does not extend TestImpl
but implements TestIfc
)?
SomeOtherTestImpl<TestFoo> testImpl = ...;
And then you try to call the of
method like this:
TestFoo testFoo = testImpl.of();
Can you see the problem here? Your of
method returns a TestImpl
, but you expect it to return a TestFoo
because T
is TestFoo
. The compiler stops you from doing that. Again, you should just get rid of the generics:
public TestImpl of() {
return new TestImpl(); //This works now
}
This problem is caused simply because you named your type parameter the same thing as your class - Type
. When you changed the name of your type parameter to, say, T
, it'll work because now Type
is the name of a class. Before, your type parameter Type
was hiding the class Type
.
However, again, there is no need for a type parameter, since, you can just do this, and it'll satisfy all constraints.
public class SubClass implements SuperIfc<Type> {
@Override
public Type create() {
return Type.of();
}
}
The unchecked assignment is because you didn't provide type arguments to SubClass
when you did
SuperIfc<Type> object = new SubClass();
This can be fixed by either explicitly giving Type
to SubClass
:
SuperIfc<Type> object = new SubClass<Type>();
or by putting in an empty diamond (which I much prefer). This second approach means that the compiler can infer by itself that by new Subclass<>()
, you mean new Subclass<Type>()
.
SuperIfc<Type> object = new SubClass<>();
Why the compiler complains:
That constructor call ( new Subclass()
) is basically like calling a method that looks like public SubClass makeNewSubClass() {...}
. In fact, let's replace that statement above with this one, which will cause the same warning.
SuperIfc<Type> object = makeNewSubClass();
SubClass
normally takes 1 type parameter (call it T
), but here, it's not given any type parameters. That means that T
could be anything, any class that extends Type
(because of the constraint SubClass<T extends Type>
).
You might thinking that if T
is always going to be a subclass of Type
, it should work all right, because the type of object
above is SuperIfc<Type>
. Assume there's a class like this - class TypeFoo extends Type
- and that the method makeNewSubClass
actually returns an object of type SubClass<TypeFoo>
( new SubClass<TypeFoo>()
).
Because of this, you expect object to be SuperIfc<Type>
but it's actually SubClass<TypeFoo>
. You probably think that that's all right, because after all, TypeFoo
is a subclass of Type
, right? Well, Java's generics are actually invariant , which means that for the compiler, SubClass<TypeFoo>
is not a subclass of SuperIfc<Type>
- it thinks they're 2 completely unrelated types. Don't ask me - I have no idea why:). Even SubClass<TypeFoo>
isn't considered the same as or a subclass of SubClass<Type>
!
That's why the compiler emits a warning - because raw types (that's what you call it when you have new SubClass()
without giving type arguments) could represent anything. As for why it emits a warning and not an error - generics were introduced in Java 5, so for code before that to compile, the compiler lets you off with just a warning.
According to the error, the type argument you gave ( TypeImpl
) should extend Type
. This is because you defined SubClass
as class SubClass<T extends Type>...
. Here, you are giving TypeImpl
as an argument for T
, and so TypeImpl
must extend Type
, so all you need to do is put do class TypeImpl extends Type
to solve that particular error.
However, even after you do that, you'll get an "incompatible types" error because, as I said earlier when talking about Problem 2, SuperIfc<Type>
is not considered a supertype of SubClass<TypeImpl>
even if TypeImpl
extends Type
.
You can do this
SuperIfc<TypeImpl> object = new SubClass<TypeImpl>();
or you can do this
SuperIfc<? extends Type> object = new SubClass<TypeImpl>();
In the second solution, we lose the information of what exactly T
is in SuperIfc<T>
; all we know is that it extends Type
. The benefit of the second one is that you can later reassign any SubClass
object to it (which doesn't work with the first version because it only allows SubClass<TypeImpl>
:
SuperIfc<? extends Type> object = new SubClass<TypeImpl>();
object = new SubClass<Type>(); //works great
What it seems like you want to do is return objects of different type depending on type parameters. That's not really possible to do, since type parameters are erased at runtime. There are workarounds, though.
Here's one way to do it with a functional interface. It involves no casting and ensures type safety.
//This is the functional interface. You can also use Supplier here, of course
interface Constructor<T> {
T create();
}
class SubClass<T extends Type> implements SuperIfc<T> {
public Constructor<T> ctor;
public SubClass(Constructor<T> ctor) {
this.ctor = ctor;
}
@Override
public T create(Object label) {
return ctor.create();
}
}
class Type {}
class TypeImpl extends Type{}
By using a Constructor
object, you will know that the returned Type
object will always be of the right type. This is very easy to apply to your existing code - you don't need to write your own ConstructorImpl
classes or anything.
You can now write this, and all you need to add is a method reference to the constructor ( Type::new
).
SuperIfc<Type> object1 = new SubClass<>(Type::new);
SuperIfc<? extends Type> object2 = new SubClass<>(TypeImpl::new);
With lambdas, you can also write this in a slightly more verbose way:
SuperIfc<TypeImpl> object = new SubClass<>(() -> new TypeImpl());
---
SuperIfc<? extends Type> object = new SubClass<>(() -> new TypeImpl());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.