【问题标题】:I don't seem to understand the super() Keyword and it's usage quite well我似乎不理解 super() 关键字,它的用法很好
【发布时间】:2019-09-24 03:07:27
【问题描述】:

我知道你在从另一个类继承时使用它,并且你必须首先在构造函数中调用它,如果我不手动调用它,也会自动调用一个空的 super() 方法。

例如,我们有一个名为 bank 的父类:

public class bank implements Comparable<bank> {
        private String owner;
        public String money;
        public boolean intheCubby;

public bank(String name, String ownersName) {
        owner = ownersName;
        money = name;
    }

还有一个名为 Account 的子类:

public class Account extends bank {

    private int totalquantity;
    public int neededquantity;

    public Account(String name, int n) {
        super(name, name);
        money = name;
        totalquantity = n;

    }

    public Account(String name, int n, String ownersName) {
        super(name,ownersName);
        money = name;
        totalquantity = n;
        setOwner(ownersName);

    }

所以我知道它的工作原理是这样的,您在 Parentclass 中有带有 2 个字符串参数的银行构造函数。 你的超级();因此,该方法还应包含 2 个字符串类型的参数。 但是如果子类的构造函数只有 (String, int) 参数,我应该将 (String, null) 放入我的 super();方法?因为我必须插入其他内容,所以会出现错误。

【问题讨论】:

  • null 对于像 int 这样的原始类型不是有效值

标签: java class inheritance methods polymorphism


【解决方案1】:

您必须从子类构造函数中调用超类的构造函数之一。

如果超类只有一个构造函数接受两个Strings,则必须从子类构造函数调用该构造函数。您的子类的构造函数应决定将哪些 String 实例传递给超类构造函数。

在你的例子中,

public Account(String name, int n, String ownersName) {
    super(name, ownersName);
    ...
}

会起作用的。

public Account(String name, int n) {
    super(name, "someDefaultValue"); // or super(name, null);
    ...
}

也可以。

【讨论】:

  • 所以我的理解是我可以调用 Account(arguments);在另一个 Account 构造函数中?
  • @SupEldrix 可以,只要其他构造函数调用现有的超类构造函数(即使用正确数量和类型的参数调用 super(...))。
【解决方案2】:

Bank 类只有一个带有nameownersName 参数的构造函数。因此,当从Account 类调用super() 时,您必须决定如何初始化这两个参数。如果您在Account 中没有ownersName,您确实可以将null 作为第二个参数传递。如果 Bank 类真的依赖于设置的 ownersName,这可能会导致问题。

我也觉得 Account 扩展 Bank 很奇怪,因为账户并不是真正的银行。但我可能在这里遗漏了您设计的完整背景。如果宁愿期望银行是Account 的字段,或者Bank 具有ArrayList&lt;Account&gt; 字段。

【讨论】:

  • 我只需要做一个简单的例子,它不是我正在开发的真实程序,我只是想重现我的问题。
【解决方案3】:

在这种情况下,使用 this(); 链接构造函数;本来是 最佳。

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多