user1953825
user1953825

Reputation:

Does a subclass constructor require all arguments of superclass constructor?

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?

Upvotes: 1

Views: 5492

Answers (3)

Daniel Kaplan
Daniel Kaplan

Reputation: 67310

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.

Upvotes: 1

William Gaul
William Gaul

Reputation: 3181

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.

Upvotes: 3

Iłya Bursov
Iłya Bursov

Reputation: 24146

No, you have to provide all arguments to function/constructor

Upvotes: 1

Related Questions