java - 在子类中隐藏父类(super class)的字段

标签 java field mask superclass

假设我有 3 个类:

class Foo
{    
    protected String var;
    public void doSomething()
    {
         // does something with var
    }
}

class A extends Foo
{
    public void doSomething()
    {
        // uses var slightly differently to Foo
    }
}

class B extends Foo
{
    protected int var; // hides Foo's var field
    public void doSomething()
    {
        // does something with B's var, but still in a similar fashion to Foo
    }
}

在这种情况下,我知道并希望 B 的 var 字段隐藏 Foo 的并且仍然以类似的方式使用(打印它的值或执行一些计算或其他)。
故意隐藏字段会使代码难以阅读,但这是一个异常(exception),还是它仍然只是糟糕的设计?

编辑:
我确实希望 A 从 Foo 继承“var”,但我也希望 B 继承除 var 之外的所有内容。

编辑 2:
忘记给 var 添加访问修饰符。

最佳答案

您不能像覆盖方法一样“覆盖”字段。您需要使用方法覆盖来实现此行为。例如:

class Foo
{    
    private String var;

    Object getVar() {
        return var;
    }
}

class B extends Foo
{
    private int var;

    @Override
    Object getVar() {
        return var;
    }
}

编辑:根据您的评论:

Foo's var is of type List<String>, and B's var is of type List<Item> where Item is a separate class all together. As you can tell, both use Lists but with different template types, and both still do the same thing (go through the list and do something to the elements)

听起来你的类应该是通用的,例如:

abstract class Foo<T> {

    List<T> list;

    // common logic
}

class A extends Foo<String> { }

class B extends Foo<Item> { }

不要从字面上理解这段代码 - 它只是建议可能的设计。

关于java - 在子类中隐藏父类(super class)的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17729371/

相关文章:

java - 未找到 Spring 应用程序上下文

java - 如何将 @SpringBootTest(webEnvironment) 与 @DataJpaTest 一起使用?

c++ - 平均两幅带掩码的图像

mysql - 更新mysql字段中的单个字符

Solr - 将分析器的结果写入不同的字段

python - 如何使用 Matplotlib 从轮廓到图像蒙版

ios - 我如何(成功地)将 maskView 设置为 UIView?

java - 使用 Java 8 流处理嵌套集合

java - EJB 和使用二进制文件 - 最佳实践

java - 如何使java流畅界面中的方法首先弹出?