: Hi there,
:
: I have a simple question involving member inheritance in Java; I was wondering what the best way of tackling this sort of design issue is. I will describe an example.
:
: There are two types of Gun, a simple one, used by Soldiers:
:
: class Gun {}
:
: and an advanced one, SilencedGun which only Commanders can use. SilencedGun is a subclass of Gun:
:
: class SilencedGun extends Gun { }
:
: Now, a Soldier is defined as:
: class Soldier {
: ???? Gun gun; // see later
:
: public void setGun(Gun g) {
: gun = g;
: }
: public Gun getGun() {
: return gun;
: }
: }
:
: class Commander extends Soldier {
: ...
: }
:
: My question is this: How do we best code a Commander class, such that only SilencedGuns can be possessed by a commander, and never simply a Gun? If we leave the Commander class empty, then any client can call commander.setGun(new Gun()), which we don't want to happen. What access specifier should gun in the parent class have?
:
: Should I overwrite gun in Commander to be of type SilencedGun, and then add new get/set of type SilencedGun? Will that stop clients calling the superclass methods?
:
: What is the best solution to this sort of issue?
:
: Thanks for suggestions.
: GS
: