A new usage of this() !
All Java developers know the this()-method, which is used to call a constructor of a class within another one. It is the only Java-method with a return value constrained to the actual class (a.k.a. self-type).
Imagine if we could use the parameterless version (even if there is no such constructor) within a method. As this, it would return a reference of the class, but virtually typed.
What about the benefits?
This simple, but powerful language extension would allow virtual calls to static methods!
Let's take a look at this example.
Without the new this()-method, one would have to override every method calling the static method, which we want to be virtual. Here, one would have to remove all comment to maintain the output:
One: static(0) - virtual(1)
Two: static(0) - virtual(2)
What do you think, is it worth to submit a RFE?
At least no new keyword or anything else have to introduced and the meaning is widely consistent with the constructor.
Imagine if we could use the parameterless version (even if there is no such constructor) within a method. As this, it would return a reference of the class, but virtually typed.
What about the benefits?
This simple, but powerful language extension would allow virtual calls to static methods!
Let's take a look at this example.
Without the new this()-method, one would have to override every method calling the static method, which we want to be virtual. Here, one would have to remove all comment to maintain the output:
One: static(0) - virtual(1)
Two: static(0) - virtual(2)
What do you think, is it worth to submit a RFE?
At least no new keyword or anything else have to introduced and the meaning is widely consistent with the constructor.

4 Comments:
I can't see a positive use for this. Can you show a use case?
Well, not really.. that's why I wondered if it's a worth feature..
The only thing I can think of are classes with stateless operation, e.g.:
class Math
{
static int add(int left, int right) { return left + right; }
static int negate(int value) { return -value; }
static int subtract(int left, int right) { return this().add(left, this().negate(right)); }
}
class Weird2Math extends Math
{
@Override
static int negate(int value) { return value; }
}
However, there is no real need.
You don't get a "Constructor call must be first statement in a constructor" error or anything like that?
Of course, its a proposed new usage, to allow to cal this() within static methods, where it should not cosntruct a new object, but return the self-type.
Post a Comment
Links to this post:
Create a Link
<< Home