问题
I have two classes, Staff and AdvancedStaff, which extends the former.
Staff has this constructor:
public Staff (String number, String title, String name, String role, char level) {
staffNumber = number;
staffTitle = title;
staffName = name;
staffRole = role;
payScaleLevel = level;
}
I'll note that all instance variables have been set to private.
While, Advanced Staff has this constructor:
public AdvancedStaff (String number, String title, String name) {
super(number, title, name);
role = "Entry level Advanced Staff";
level = 'A';
}
However, this throws a "symbol not found" error for my Staff constructor.
I've tried using super.staffRole = "Entry level Advanced Staff"; but the private scope of my superclass prevents this.
I've found that adding the fields String role and char level to my AdvancedStaff constructor allows me to call the super constructor, but I'm wondering if there's a way to call the super constructor without passing all of its arguments in my subclass constructor?
回答1:
You have to provide all arguments to the constructor.
In your case, you still can call the constructor of Staff, but you must provide some default values, like so:
super(number, title, name, "Entry level Advanced Staff", 'A');
This does the same work as what you're already doing in the constructor for AdvancedStaff, only now it's the Staff class setting the values of the private variables, since you're passing it via the constructor.
On a side note, if you plan on accessing these private variables from a subclass, you should really make them protected instead.
回答2:
No, you have to provide all arguments to function/constructor
回答3:
You either need to take @WilliamGaul's advice or create a new constructor in the parent that only accepts the 3 arguments you want to pass in. Which one to choose depends on the context.
来源:https://stackoverflow.com/questions/19415998/does-a-subclass-constructor-require-all-arguments-of-superclass-constructor