简体   繁体   English

为什么类返回自身的实例?

[英]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 我还有另一门课叫做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. MHandle类或它的具体子类(例如House )的内部,以及在那些不能访问MHandle类的类的内部。 I don't see the point of having getMHandle() at all, if all it does is return a self-reference without doing anything useful . 我根本看不到具有getMHandle()的意义,如果它所做的只是返回一个自引用而不做任何有用的事情

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". 还有一种类似的应用,称为“ getThis()技巧”。 It is related to the covariance aspect, and explained here in detail: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206 它与协方差方面有关,在此处详细说明: http : //www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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