Override a property in Java [duplicate]

心已入冬 提交于 2020-01-05 03:36:25

问题


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;
 }
}

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.

Something like this:

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?


回答1:


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;
    }
}

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.



来源:https://stackoverflow.com/questions/38163255/override-a-property-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!