2

Why does this code not compile?

public class Wrapper<T> extends T {}

Is it because this is semantically never a proper design choice? Or can this physically not compile in any language because of some sort of type ambiguity?

I'd imagine you could use it to create a public class Persistent<T> extends T {} that allows you to for example extend the T with some functionality to serialize the T to a byte array and store it on disk, while still allowing instances of Persistent<T> to be passed to functions that would otherwise only take values of type T.

As such this would be possible: EDIT: this would not be possible, as there could be no sensible implementation for load() (as correctly pointed out by michid). To not corrupt his comment though, I'll leave it here.

Integer i1 = Integer.valueOf(5);
Persistent<Integer> i2= new Persistent<Integer>();
i2.load(i1) //example method to load i1 into i2, basically serializing it

List<Integer> myIntegers = new ArrayList<>();
famousPeople.add(i1);
famousPeople.add(i2);
Adriaan Jacobs
  • 309
  • 2
  • 9
  • How would `Persistent` know how to serialize `T`? `T` can be anything. E.g. `Void` or `InputStream` or `Integer` but you cannot know that when implementing `Persistent`. – michid Apr 18 '20 at 20:30
  • Can't this be done using a `ObjectOutputStream` and/or the `Serializable` interface? https://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array – Adriaan Jacobs Apr 18 '20 at 20:36
  • How would you implement `load()` in your example above? – michid Apr 18 '20 at 20:40
  • I see what you mean. I just tried it, and I can't find a way to do it, you are right. Is this also the answer why it isn't possible to do this? Is there just no way to write any code in this Wrapper class? – Adriaan Jacobs Apr 18 '20 at 20:47
  • 1
    Whether this is also the answer why it isn't possible I don't know. The designers of Java must have had reasons to disallow this. The one I have given might be one of them. – michid Apr 18 '20 at 21:16

1 Answers1

3

When you extend a class you extend the existing functionality by some additional one provided by the super class. When the super class is T it can be anything but you cannot know what. So how would you extend something you know nothing about?

michid
  • 10,536
  • 3
  • 32
  • 59
  • In some cases we could just be happy with the public interface of the `Object` class and for example re-implement the toString() method to add something to the existing toString() implementation (if any) of T, allowing us to basically "extend" any class at runtime by creating this kind of wrapper around it? I'm not saying it's useful, but why is it strictly not allowed? – Adriaan Jacobs Apr 18 '20 at 20:43
  • @AdriaanJacobs If you want a wrapper, then create a class `Wrapper` and wrapp whatever you want; put everything there. Doing something like that with inheritance is inherently wrong. The answer of @michid explains why. – akuzminykh Apr 18 '20 at 20:54