覆盖Java中的属性 [英] Override a property in Java

查看:196
本文介绍了覆盖Java中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,最近我有几个项目使用了这样的设计模式:

In Java, I have had several projects recently where I used a design pattern like this:

public abstract class A {
 public abstract int getProperty();
}

public class B extends A {
 private static final int PROPERTY = 5;

 @Override
 public int getProperty() {
  return PROPERTY;
 }
}

然后,我可以在类A的任何成员上调用抽象方法getProperty().但是,这似乎很麻烦-似乎应该有某种方法可以简单地重写属性本身,以避免在扩展A的每个类中复制getProperty()方法.

Then I can call the abstract method getProperty() on any member of class A. However, this seems unwieldy - it seems like there should be some way to simply override the property itself to avoid duplicating the getProperty() method in every single class which extends A.

类似这样的东西:

public abstract class A {
 public static abstract int PROPERTY;
}

public class B extends A {
 @Override
 public static int PROPERTY = 5;
}

像这样可能吗?如果是这样,怎么办?否则,为什么不呢?

Is something like this possible? If so, how? Otherwise, why not?

推荐答案

您不能覆盖"字段,因为只有方法可以覆盖(并且不允许将它们静态或私有).

You cannot "override" fields, because only methods can have overrides (and they are not allowed to be static or private for that).

通过使该方法成为非抽象方法,并为子类设置一个受保护的字段,可以实现所需的效果,如下所示:

You can achieve the effect that you want by making the method non-abstract, and providing a protected field for subclasses to set, like this:

public abstract class A {
    protected int propValue = 5;
    public int getProperty() {
        return propValue;
    }
}

public class B extends A {
    public B() {
        propValue = 13;
    }
}

此技巧使A的子类将新值推"到其超类的上下文中,获得与覆盖"相似的效果,而没有实际的覆盖.

This trick lets A's subclasses "push" a new value into the context of their superclass, getting the effect similar to "overriding" without an actual override.

这篇关于覆盖Java中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆