return this from a generic method generalized with <T extends TestClass>

java generic method return type
java generic method parameter
java generic method example
java generic method parameter extends
java call generic method
java generic static method
generic method c#
generic method in non generic class java

Why can't I do this in Java:

public class TestClass {

    public <T extends TestClass> T test(){
        return this; // error here

As I understand, this will always be an instance of some class that extends TestClass, so why the code above is not allowed by compiler? Even if I will extend the TestClass then type of this will fit extends TestClass anyway. I get the following error:

Error:(4, 16) java: incompatible types: TestClass cannot be converted to T

Say you have SubTestClass extends TestClass, and you write:

TestClass instance = new TestClass();
SubTestClass result = instance.test();

This is legal regarding the signature of your test() class, although nonsense (1). The compiler will deduce that T is the class SubTestClass. And then it's clear that a TestClass instance isn't instanceof SubTestClass. So with legal usage of your test() method, returning this can produce type mismatches, and that's what the compiler tells you.

With your test() signature, it's impossible to return anything other than null, because null is the only value you can assign to a variable of unknown type.

Let me explain that last claim (asked for in comments): The implementation of the test() method has to return some value that matches the T type, and the concrete type (deduced from the call situation to be SubTestClass) isn't deducible to the method - there's nothing in the arguments or in the instance fields where it can read out the requirement to return a SubTestClass in this situation. In another call situation, it might be required to return AnotherSubTestClass, and there's no way it can tell the first from the second situation.

If you return this (with (T) casting to make it pass the compiler), it will fail either in the first or in the second or in both situations. So you can't do that without high risk of failure.

The only value that you can successfully assign to both a SubTestClass and a AnotherSubTestClass variables, is the null value. So that's the only value you can safely return from a method with such a signature.

(1) Having a generic method where the generic type can't be deduced from the parameters, but instead only from the expected result type, can hardly work - how should the method know what the caller expects?

Generic Methods (The Java™ Tutorials > Bonus > Generics), The way to do deal with these problems is to use generic methods. The return type doesn't depend on the type parameter, nor does any other argument to the  Here, in this article, I try to explain Generalized Async Return Types in C# step by step with some simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Generic Methods (The Java™ Tutorials > Learning the Java , The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic  Indeed, we have managed to have methods that only work when the type parameter meets certain restrictions. Mainly the generalized type constraints serve to ensure that a specific method has a concrete constraint, so that certain methods can be used with one type and other methods with another.

"this" represents the class "TestClass",because TestClass is T's superClass,superClass cannot be converted to subClass,but you can try Forced type conversion,or Set the return type to "TestClass".

public <T extends TestClass> T test() {
    return (T)this;

edit 01: forced cast is wrong,it It may cause runtime errors.

How do I make the method return type generic?, Here's some initial code with return type conveyed to the method as a parameter that's never used. public<T extends Animal> T callFriend(  Generalized async return types and ValueTask<TResult> Starting with C# 7.0, an async method can return any type that has an accessible GetAwaiter method. Because Task and Task<TResult> are reference types, memory allocation in performance-critical paths, particularly when allocations occur in tight loops, can adversely affect performance.

How to write generic classes and methods in Java, This Java Generics tutorial helps you design highly general and reusable type in the save() method and as a return type in the get() method. Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem. Here is the method Collections.copy():

Generic Methods, A generic method is a method that is declared with type parameters, it cannot infer the type parameters only from a constraint or return value. Features of Generics. Generics is a technique that enriches your programs in the following ways − It helps you to maximize code reuse, type safety, and performance. You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace.

Java - Generics, Java - Generics - It would be nice if we could write a single sort method that could sort The type parameters can be used to declare the return type and act as Following example illustrates how extends is used in a general sense to mean  Generics (C# Programming Guide) 07/20/2015; 3 minutes to read +8; In this article. Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

  • Perhaps you could give us some more information about the context (what you want to achieve), so when can suggest alternative ways instead of only explaining why your approach doesn't work.
  • @RalfKleberhoff It is kind of a research question. Roughly speaking I investigate simulated self-type idiom from Effective Java by Joshua Bloch (Item 2) and methods chaining in particular.
  • Looks close, but it is not true that I can't return anything other than null. I can cast this to T.
  • Try it yourself ;-). With casting this to T, it still is a TestInstance, and not a SubTestInstance. Casting doesn't change the instance, it's just a developer's promise that the instance has the correct type, and this promise doesn't hold.
  • I mean, it will of course fail in runtime, but compile is ok.
  • I consider failing in runtime far worse. All the compiler checks are there to find potential runtime problems as early as possible.
  • Sure, runtime fail is far worse. I just can't understand your phrase properly: impossible to return anything other than null. Your (1) notice is quite valuable, but I am still ponder it.
  • Now you've moved the problem from the compiler to a runtime error.
  • What do you mean by "Forced type conversion"?
  • It's a cast, and this is broken. If you cast this you're basically ignoring the very sane and reasonable type advice that the compiler is trying to provide for you and you move this to a runtime error.
  • @RalfKleberhoff forced cast.