简体   繁体   English

如何在Java抽象类中声明未初始化的变量?

[英]How to declare uninitialized variable in abstract class in Java?

I want to declare an abstract class which has a variable to be initialized in its subclasses. 我想声明一个抽象类,该类具有要在其子类中初始化的变量。 For example, let's say we have an abstract class called Country, and a subclass called United States. 例如,假设我们有一个名为Country的抽象类和一个名为United States的子类。 (I know, usually you'd make United States an instance of Country, but I'm just using this as an example so let's assume this is the design we are going for.) I want to have a public final Set<String> called bigCities which is declared but uninitialized in Country, but will be initialized in United States as something like {"New York", "Los Angeles", "Chicago"}. (我知道,通常您会将美国作为Country的一个实例,但是我仅以此为例,所以我们假设这是我们要使用的设计。)我想要一个public final Set<String>称为bigCities,在Country中已声明但尚未初始化,但在美国将被初始化为{“ New York”,“ Los Angeles”,“ Chicago”}之类的名称。 How would I accomplish this? 我将如何完成?

(I apologize if it's been asked before, but my question is rather difficult to formulate precise search terms for. Every time I've tried to search on Google or StackOverflow I've gotten questions that are similar to but not what I'm looking for.) (很抱歉,以前是否有人问过我,但我的问题很难为其指定精确的搜索词。每次我尝试在Google或StackOverflow上进行搜索时,都会遇到与我所寻找的问题类似但与我所寻找的问题类似的问题对于。)

If you want to define your property bigCities as final it has to be initialized within the constructor of the class, either Country or UnitedStates in your case. 如果要将属性bigCities定义为final ,则必须在类的构造函数中初始化,在您的情况下为CountryUnitedStates

public abstract class Country {
  public final Set<String> bigCities;
  public Country(Set<String> bigCities) {
    this.bigCities = bigCities;
  }
}

In that case the subclass of Country has to call the the parent's constructor with the specified argument. 在这种情况下, Country的子类必须使用指定的参数调用父级的构造函数。

There are two ways you can do this. 有两种方法可以执行此操作。 You can have the Country constructor have a parameter called bigCities, and a subclass such as the UnitedStates would call super(cities, otherArgs). 您可以使Country构造函数具有一个名为bigCities的参数,并且一个子类(例如美国)将调用super(cities,otherArgs)。

Alternatively, you can make an abstract method like this 或者,您可以制作一个像这样的抽象方法

protected abstract Set<String> getBigCities();

and then in the Country constructor, set bigCities to the implementation of that method. 然后在Country构造函数中,将bigCities设置为该方法的实现。

bigCities = getBigCities();
abstract class Country {

    public final Set<String> bigCities;

    protected Country(String... bigCities) {
        this.bigCities = new HashSet<String>(Arrays.asList(bigCities));
    }

}

class USA extends Country {
    USA() {
        super("NY", "Chicago");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM