子类构造函数是否需要超类构造函数的所有参数? [英] Does a subclass constructor require all arguments of superclass constructor?

查看:117
本文介绍了子类构造函数是否需要超类构造函数的所有参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班级,员工 AdvancedStaff ,这扩展了前者。

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

员工有这个构造函数:

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';
    }

然而,这会为我的<$ c引发找不到符号错误$ c>员工构造函数。

However, this throws a "symbol not found" error for my Staff constructor.

我尝试过使用 super.staffRole =入门级高级员工; 但是我的超类的私有范围阻止了这个。

I've tried using super.staffRole = "Entry level Advanced Staff"; but the private scope of my superclass prevents this.

我发现添加字段字符串角色 char level 到我的 AdvancedStaff 构造函数允许我调用超级构造函数,但我是想知道是否有办法调用超级构造函数而不在我的子类构造函数中传递它的所有参数?

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?

推荐答案

你必须提供构造函数的所有参数。

You have to provide all arguments to the constructor.

在你的情况下,你仍然可以调用 Staff 的构造函数,但你必须提供一些默认值,如下所示:

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');

这与你在 AdvancedStaff ,现在只有 Staff 类设置私有变量的值,因为你是通过构造函数传递的。

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.

另外,如果您打算从子类访问这些私有变量,您应该确实将它们设为 protected

On a side note, if you plan on accessing these private variables from a subclass, you should really make them protected instead.

这篇关于子类构造函数是否需要超类构造函数的所有参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆