title: Java: Is casting to generic type in parent class safe when generic is <T extends Parent>?
body: <p>I have a parent class for all of my custom exceptions, ParentException. I want all child exceptions to have a method that adds a message to the exception. To do this I created a generic method that returns an object of generic type after adding the message to it. I use <code>this</code> in the parent class method to add the message then return <code>this</code> but since the method returns the generic type I casted it to the generic type T. This seems to work, but gives a warning. My code is as follows:</p>
  
  <pre><code>public class ParentException extends RuntimeException{
  
      private String message;
  
      public ParentException() {
          message = "";
      }
  
      public void addToMessage(String msg) {
          message += msg;
      }
  
      public void printMessage() {
          System.out.println(message);
      }
  
      public &lt;T extends ParentException&gt; T withMessage(String msg) {
          this.addToMessage(msg);
          return (T) this; // This line gives the warning
      }
  }
  </code></pre>
  
  <p>The warning given by that line is <code>Unchecked cast from ParentException to T</code>. The method does seem to work as expected, so I'm not worried but I'd like a better understanding of why this gives a warning in the first place.</p>
  
  <p>Will this cast always be safe? Otherwise what case would cause a runtime error?</p>