Java – override generic methods using non generic implementations

I was trying generics in Java and thought of this example

If I have classA < T >, I can override it with Subclasses referencing specific classes. For example, ClassB extends classA < string >, then classA uses T and ClassB can use string

Now, ignore the previous classA and ClassB. If I have an abstract classA, it has a general method:

public <T> void doSomething(T data);

Is there any way for ClassB to override it with a specific class, similar to the previous example? I came up with some useful things, namely parameterized classes and methods, but I wonder if there is another method

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

The reason why I don't want to put parameters in the class is because it has only one method that can perform any operation on the type, and some subclasses may not even want to perform any operation in the method, so I don't need to put parameters in the class if it doesn't intend to use it

Note: all subclasses of classA are anonymous, so it adds fun

Solution

Thank you for this:

public <T> void doSomething(T data);

It really means:

public void doSomething(Object data);

So no, there is no way to override with more strict parameter types

Also in this Code:

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

The type parameter in the class name and the type parameter in the method are actually different parameters This is like declaring a local variable with the same name as a variable in a higher range You can call dosomething (123) on the instance of classA < string >, because the second t is the local of the method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>