Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

java - Overriding generic methods with non-generic implementations

I'm experimenting with generics in Java, and thought of this example.

If I have ClassA<T>, I can override it with a subclass that references a concrete class, such as ClassB extends ClassA<String>, then anywhere ClassA uses T, ClassB can use a String.

Now, ignoring the previous ClassA and ClassB, if I have an abstract ClassA, which has a generic method:

public <T> void doSomething(T data);

Is there any way I can have a ClassB that overrides it with a concrete class, similar to the previous example? I've come up with something that works, which is to parameterize both the class and the method, but I'm wondering if there's another way.

class ClassA<T> {
    public void doSomething(T data) {};
}

The reason I don't want to put the parameter in the class is because it's only one method that does anything with that type, and some subclasses may not even want to do anything in that method, so I shouldn't need to put a parameter in the class if it's not going to use it.

NOTE: All of the subclasses of ClassA are anonymous classes, so that adds to the fun.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thanks to type erasure, this:

public <T> void doSomething(T data);

Really means this:

public void doSomething(Object data);

So no, there isn't a way to override with a more restrictive parameter type.

Also in this code:

class ClassA<T> {
    public <T> void doSomething(T data) {};
}

The type parameter in your class name and the type parameter in the method are actually different parameters. It's like declaring a local variable of the same name as a variable in a higher scope. You can call doSomething(123) on an instance of ClassA<String> because the second T is local to the method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...