简体   繁体   中英

Why does a class return an instance of itself?

I have an abstract class..

public abstract class MHandle {
    public MHandle getMHandle(){
        return this;
    }
}

I also have another class called House

public class House extends MHandle{
    public void methodA(){
    }
}

what would be the point of doing something like

public void methodA(){
    MHandle mh = getMHandle();
}

There is absolutely no difference between this:

public void methodA(){
   MHandle mh = getMHandle();
   mh.toString();
}

and this

public void methodA(){
   this.toString();
}

and this

public void methodA(){
   toString();
}

and this

public void methodA(){
   this.getMHandle().getMHandle().getMHandle().getMHandle().
      getMHandle().getMHandle().toString();
}

This non-difference is true in any context. Internally to the MHandle class or its concrete sub-classes (such as House ), and also to classes that do-or-don't have access to the MHandle class. I don't see the point of having getMHandle() at all, if all it does is return a self-reference without doing anything useful .

One aspect could be covariance: This method can be overridden to return a more specific type:

public abstract class MyMoreSpecificHandle extends MHandle {
    public MyMoreSpecificHandle getMHandle(){
        return this;
    }
}

There is also an application of something like this known as "The getThis() trick". It is related to the covariance aspect, and explained here in detail: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206

这将返回House实例,因为它扩展了MHandle。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM