【问题标题】:Using this keyword in abstract context在抽象上下文中使用 this 关键字
【发布时间】:2013-08-11 15:46:28
【问题描述】:

我在一些源代码中遇到过这种模式:

public abstract class Foo {

    void doSomething(){
        System.out.println("...");
    }

    private class FooBar extends Foo{
        void doAnything(){
            Foo.this.doSomething();
        }
    }
}

有什么意义

Foo.this.doSomething();

还是只是一些货物崇拜的做法?

【问题讨论】:

    标签: java


    【解决方案1】:

    Foo.thisthis 指的是两个不同的对象。

    由于FooBar 是在Foo 中定义的内部类,因此FooBar 的每个实例都有一个与之关联的Foo 实例。

    • this 指的是 FooBar 实例本身;
    • Foo.this 指的是外部 Foo 实例。

    How can "this" of the outer class be accessed from an inner class?

    也就是说,您展示的示例中的Foo.this. 是多余的,可以省略(除非FooFooBar 都有一个名为doSomething() 的方法)。

    【讨论】:

      【解决方案2】:

      在你给出的例子中,这相当于直接调用doSomething();

      但是,如果您在 FooBar 类中声明了相同的方法 void doSomething(),您将使用此表示法表示您调用的是外部类的方法而不是内部类。

      在后一种情况下this.doSomething() 是不够的,它仍然会指向FooBar 的成员变量this,这就是为什么您要专门指定要从中调用方法的类。

      【讨论】:

        【解决方案3】:

        Foo.this 引用外部类 Foo 的对象实例,它总是绑定在内部类的对象中。

        当 Foo 被实例化时,你可以认为 Foo 和 FooBar 总是一起被实例化。

        在你的情况下是没有必要的,但是如果你需要将 Foo 对象实例传递给任何需要它从内部 Foo.Bar 的方法,你可以这样做:

        // some method of some other class (OtherClass.java)
        void someFunction( Foo foo )...
        
        // ...
        private class FooBar extends Foo{
            void doAnything(){
                otherClass.someFunction( Foo.this );
            }
        }
        

        【讨论】:

          【解决方案4】:

          Foo.this指的是外部类对象,而this指的是当前类对象。
          根据java的docs。也叫Shadowing

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-06-22
            • 1970-01-01
            • 2015-06-25
            • 2020-12-28
            • 1970-01-01
            • 2015-02-28
            • 1970-01-01
            • 2023-03-22
            相关资源
            最近更新 更多