Tony
Tony

Reputation: 246

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. (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"}. 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.)

Upvotes: 3

Views: 2721

Answers (3)

user3329098
user3329098

Reputation:

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

Upvotes: 1

kabb
kabb

Reputation: 2502

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).

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.

bigCities = getBigCities();

Upvotes: 1

Manuel
Manuel

Reputation: 4228

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.

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.

Upvotes: 3

Related Questions