I know this isn’t a good question to ask and I might get cursed to ask it but I cannot find any place to get help on this question
Below is a Generic class that appeared in my interview question (which I have already failed). The question was to tell what this Class declaration is doing and in what circumstances this could be used for ?
I have very limited understanding of Generic programming but I understand that ‘T’ is Type and ‘extends’ here means that the Type should have inherited ‘SimpleGenericClass’ but I do not understand the ‘?’ at the end and in what circumstances this Class could be potentially used for
public abstract class SimpleGenericClass<T extends SimpleGenericClass<?>> {
}
First, because the class
SimpleGenericClassis abstract, it is meant to be subclassed.Second, it is a generic class which means that inside the class somewhere you will almost assuredly be using the generic parameter
Tas the type of a field.Now the first interesting thing here is that
Tis bounded. Because it is declared asT extends SimpleGenericClass<?>it can only beSimpleGenericClass<?>or some subclass ofSimpleGenericClass<?>. You also asked about thr?. That’s known as a wildcard and there is a pretty good explanation of it at the Java Tutorial on Wildcards. In your case we would say this is a “SimpleGenericClass of unknown.” It is needed in Java becauseSimpleGenericClass<Object>is NOT the superclass ofSimpleGenericClass<String>, for example.The second interesting thing though is that since
Tis aSimpleGenericClassof some sort, your class is more than likely defining recursive structures. What comes to my mind are trees (think of expression trees) whereSimpleGenericClassis the (abstract) node type, designed to be subclassed with all kinds of specialized node types.UPDATE This SO question on self-bounded generics might be helpful to you.
UPDATE 2
I went ahead and put together some code that illustrates how this can be used. The app doesn’t do anything but it does compile and it shows you how the generic bounds can supply some possibly-meaningful constraints.
The nice thing here is that
NumberNode[]is a valid return type forPlusNode.getChildren! Does that matter in practice? No idea, but it is pretty cool. 🙂It’s not the greatest example, but the question was rather open ended (“what might such a thing be used for?”). There are other ways to define trees, of course.