Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Objective-C instancetype?

In Objective-C, instancetype can be used as the return type of methods that return an instance of the class they are called on (or a subclass of that class).

What is the equivalent of instancetype in Java?

like image 473
Cool Avatar asked Sep 29 '22 01:09

Cool


1 Answers

The closest to thing is to use generics

interface Base<B extends Base<B>> {
    // do something and return this.
    B append(String s);
}

interface SubBase<B extends SubBase<B>> extends Base<SubBase<B>> {
    // append returns a SubBase<B>
}

class MyClass implements SubBase<MyClass> {
    public MyClass append(String s) {
         // do something
         return this;
    }
}

It's not so elegant, but it works.

like image 94
Peter Lawrey Avatar answered Oct 13 '22 17:10

Peter Lawrey