0

In abstract class i have method:

abstract void method(Holder<?> holder);

and in implementation class (there would be multiple class like this one, each with its own type - SomeClass, SomeClass2,..):

@Override
void method(Holder<SomeClass> aHolder) {...}

This doesn't work, so what point i'm missing?

There is compiler error: "Method does not override method from its superclass"

3
  • What is the exact error? Commented Apr 26, 2016 at 9:09
  • You are overriding addDocs() instead of method() Commented Apr 26, 2016 at 9:19
  • sorry, i'll correct that... "method" is the one that is actually overriden, but that wasn't the problem Commented Apr 26, 2016 at 9:29

2 Answers 2

3

The point is that an implementation of void method(Holder<?> holder) needs to be able to accept any of: Holder<SomeClass>, Holder<SomeClass2>, Holder<Void> etc

If you try to declare the method as void method(Holder<SomeClass> holder) in subclasses, that implies that you can invoke provider methods on the holder (e.g. SomeClass value = holder.get()), but that would fail with a class cast exception if the parameter is actually of type Holder<Void>, for instance.

As such, it is forbidden by the type system.

You need to have a type variable at the class level:

abstract class BaseClass<T> {
  abstract void method(Holder<T> aHolder);
}

Then you can create concrete classes:

class SomeClassBaseClass extends BaseClass<SomeClass> {
  @Override void method(Holder<SomeClass> aHolder) {}
}
Sign up to request clarification or add additional context in comments.

Comments

1

You're trying to override with a "more specific" implementation that wouldn't accept "?", it would only accept "SomeClass", therefore it would break the "contract" with the abstract class.

It's easier to understand if you think about implementing other classes that would interact with your class.
You would expect it to accept any class type because it declares "?", but if it only accepted "SomeClass" it would break your system.

You should use the generic "T" at class level instead and declare the type you're using on each implementation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.