title: Java wrapper class subclass of concrete type
body: <p>Let's say I have a class person as follows:</p>
  
  <pre><code>public class Person {
     String name;
     int age;
  }
  </code></pre>
  
  <p>and a number of subclasses such as </p>
  
  <pre><code>public class Student extends Person {
     // extra fields and methods
  }
  public class Teacher extends Person {
     // extra fields and methods
  }
  </code></pre>
  
  <p>Now, consider that for some application I need to assign an integer id to each person instance, but I don't want to extend the <code>Person</code> interface to add the getId() there and a field to hold the id. A simple solution would be to use a wrapper like:</p>
  
  <pre><code>public class PersonWrapper extends Person {
      public PersonWrapper(Person p, int id) { // assign the id and other fields }
      public int getId() { return id; }
  }
  </code></pre>
  
  <p>This way the client code still works with the Person interface and a wrapped person can be 
  treated as a person.
  The problem with this approach is that PersonWrapper is a subclass of Person and not Teacher or Student, and such a code won't work:</p>
  
  <pre><code>Teacher t = new PersonWrapper(teacher, 1);
  t.giveGrade();
  </code></pre>
  
  <p>Of course, it's possible to create concrete wrapper types for all subclasses of <code>Person</code>, but I was wondering if there is a more elegant solution. The ideal solution would be something like this:</p>
  
  <pre><code>public class PersonWrapper&lt;T extends Person&gt; extends T
  </code></pre>
  
  <p>so that any PersonWrapper is a subclass of the type it wraps, but it's not possible in Java and I
  suspect such definition may not be possible in any language.</p>
  
  <p>In any case, how can I assign ids to subclasses without changing my client code that works with person and its subclasses, without creating a concrete wrapper for each subclass?</p>