Does a subclass constructor require all arguments of superclass constructor?

后端 未结 3 1952
忘了有多久
忘了有多久 2020-12-10 23:45

I have two classes, Staff and AdvancedStaff, which extends the former.

Staff has this constructor:

public Staf         


        
相关标签:
3条回答
  • 2020-12-10 23:53

    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.

    0 讨论(0)
  • 2020-12-10 23:56

    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.

    0 讨论(0)
  • 2020-12-11 00:06

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

    0 讨论(0)
提交回复
热议问题