In your question you expressed a desire to count instances of subclasses that you create. This really isn't in the responsibilities that any of those classes would have. With your requirement, I would implement a solution something like this:
abstract class Building { }
final class Cottage extends Building { }
final class House extends Building { }
final class Castle extends Building { }
final class BuildingManager {
private final static BuildingManager _instance = new BuildingManager();
private Set<Building> buildings;
private BuildingManager() {
buildings = new HashSet<>();
}
public static BuildingManager getManager() {
return _instance;
}
public Building getNewBuilding() {
// decide which building to create, but we'll always go with
// a castle for this example
Building castle = new Castle();
buildings.add(castle);
return castle;
}
public int getBuildingCount() {
return buildings.size();
}
}
BuildingManager
is solely responsible for managing creation and counting of Building
's.
With that in place, you would use it like this:
BuildingManager manager = BuildingManager.getManager();
Building building = manager.getNewBuilding();
Building building2 = manager.getNewBuilding();
System.out.println(manager.getBuildingCount() + " buildings exist.");
which will output:
2 buildings exist.
To answer your specific questions:
I want totalNumber in Buildings class to always show the total number of buildings that have been made. Would I use the "final" keyword for the "totalNumber" field in this case?
No. A final value field couldn't be changed once initialized. You could use object to store this (kudos to @scottb to mentioning AtomicInteger
), but that doesn't change the fact that counting how many buildings exist in your application's state is outside of the responsibilities that Building
would have.
What happens if inside an object of the subclass "Cottage", cott I call cott.totalNumber = cott.totalNumber += 1? Will it update the field it inherited?
No. It would be a fair assumption that if Building
kept a counter, it would be a static field or method, and thus be something like
Building.incrementCount();
An inherited field from a superclass is still unique to that specific instance.