class A<E>{
}
class B<E> extends A{
}
public class WildInDeclare<E>{
public static void main(String[] args){
A<Integer> obj = new B<Integer>();
}
}
When I compile the above program I got this error.
Note: WildInDeclare.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
After that I just replace class B<E> extends A{
to class B<E> extends A<E>{
it works fine can you explain why it required to again write A<E>
During inheritance with code Example Please.
The second Problem with Inheritance I faced. I update the above code with the follow code.
class A<E>{
public A(E o){
}
}
class B<E> extends A{
public B(){
super(E);
}
}
public class WildInDeclare<E>{
public static void main(String[] args){
A<Integer> obj = new B<Integer>();
}
}
But it is not compiling why? I got the following error.
WildInDeclare.java:8: error: cannot find symbol
super(E);
^
symbol: variable E
location: class B<E>
where E is a type-variable:
E extends Object declared in class B
Note: WildInDeclare.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
How I can pass Parameter to Parent class?
can you explain why it required to again write A
Because A
is a generic class that takes one type parameter. Ideally, you wouldn't be able to refer to the raw type A
, you'd only be able to refer to A<String>
or A<Integer>
or A<Map<K, List<O>>
etc. Java lets you use the raw type for backwards compatibility, but in principle it should be compulsory to provide the parameter.
When you're saying that class B
extends A
, you still need to say what kind of A
it extends; ie what the generic parameter is. (This does not need to be the same as B
's generic parameter - you could for example define B<E> extends A<String>
and that would be consistent.)
the following code...is not compiling. Why?
That code is just syntactically invalid. You've defined A
's constructor to take an object of its generic parameter type. So when you call super()
from B
's constructor, you need to pass in such an object. E
is not an object - it's just the name for B's generic parameter. So the compiler is right to say "cannot find symbol", there is nothing called E
in scope.
If you wanted B
to take an input parameter that it just passes to the superclass constructor, it would look something like this:
class B<E> extends A<E> {
public B(E e) { // this parameter could be called anything, doesn't have to be e
super(e);
}
}
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.