【问题标题】:Member shadowing in subclass子类中的成员阴影
【发布时间】:2013-03-19 06:30:29
【问题描述】:

考虑以下示例大纲:

interface IBar{ /*...*/ }

class SomeBar implements IBar { /*...*/ }

abstract class AbstractFoo
{
    IBar context;

    /* Some default implementations of methods manipulating 'context' */
}

class SomeFoo extends AbstractFoo
{
    final SomeBar context = (SomeBar)super.context;       // <-- AAA

    /* Some methods that reference additional non-IBar methods. */

    // The line AAA allows us to use:
    //      context.additionalMethod()
    // instead of
    //      ((SomeBar)context).additionalMethod()
}

我的问题是关于“AAA”行。这里的目标是避免每次引用从超类继承的上下文成员时都必须强制转换。换句话说,我宁愿

context.additionalMethod()

而不是

((SomeBar)context).additionalMethod()

每次。

这种方法似乎有效,但我想知道它是否正确,或者这样做是否有任何问题。就我而言,这不会导致模棱两可,尽管我可以看到一般情况下它是如何产生的。

另外,我只是想确保我不是在这里创建新对象,而是让方法以不同方式解释 context 引用成员。

我想另一种方法是将context 重命名为rawContext,这可能更可取。

提前致谢

【问题讨论】:

  • IBar 中有additionalMethod 方法吗?
  • @Apurv:不,additionalMethod 不在IBar 中。

标签: java inheritance shadowing


【解决方案1】:

这是一个使用泛型的经典案例:

abstract class AbstractFoo<T extends IBar>
{
    protected T context;
    // some default impl
}

然后

class SomeFoo extends AbstractFoo<SomeBar> 
{
    // access context directly as type SomeBar
}

【讨论】:

  • 哇,这种方法令人大开眼界。谢谢。
猜你喜欢
  • 2017-11-08
  • 2016-02-17
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多