【问题标题】:Constructor Method overload Java构造方法重载Java
【发布时间】:2014-12-10 18:38:12
【问题描述】:

我正在尝试创建非常简单的 Rational 类。

如果在主要方法中调用Rational(2),则调用num = 2den = 1

如果有人打电话给Rational(2, 4) 那么num = 2den = 4

这是我的代码:

public class Rational {

    public long num;    
    public long den;

    Rational(long arg1, long arg2){

        num = arg1;    
        den = arg2;

    }

    Rational(long arg1){

        long x = 1;
        Rational(arg1, x);  //Rational(long, long) is undefined for type Rational

    }

}

我已经评论了我不知道如何修复的错误消息。

有什么建议吗?

【问题讨论】:

    标签: java constructor overloading


    【解决方案1】:

    您需要使用 this 关键字,但它必须是构造函数中的第一条语句,因此无法在此之前定义 x

    this(arg1, 1); 
    

    【讨论】:

      【解决方案2】:
      this(arg1, 1);
      

      您使用this 关键字调用另一个构造函数,类似于您使用super 的方式。它也必须是构造函数主体中的第一条语句。由于它是第一个,因此您必须在示例中更改传递 x 的方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-20
        • 2019-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多