简体   繁体   中英

Constructor Method overload Java

Very simple Rational class I'm trying to create.

If, in the main methods, one calls Rational(2) then num = 2 and den = 1

If one calls Rational(2, 4) then num = 2 and den = 4

Here is my code:

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

    }

}

I have commented the error message I have no idea how to fix.

Any suggestions?

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

this(arg1, 1); 
this(arg1, 1);

You call the other constructor using the this keyword, similar to how you would use super . It must also be the first statement in the constructor body. Since it is first, you will have to change the way you pass in x in your example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM