我如何引用它调用的方法中的对象?

时间:2016-12-26 20:23:25

标签: java

我创建了一个名为Rational的类,它存储了两个私有的int(numer和denom)。我正在尝试创建一个方法,该方法返回一个新的Rational对象,该对象包含调用该方法的对象的倒数。

class Rational{

private int numer;
private int denom;

//sets numerator and denominator
public Rational (int numer, int denom){
    this.numer = numer;
    this.denom = denom;     
}

//copy constructor for a Rational object
public Rational (Rational copy){
    this(copy.getNumer(), copy.getDenom());
}

//sets numerator to parameter
public void setNumer(int numer){
    this.numer = numer;
}

//returns the stored numerator
public int getNumer(){
    return this.numer;
}

//sets denominator to parameter
public void setDenom(int denom){
    this.denom = denom;
}

//returns the stored denominator
public int getDenom(){
    return this.denom;
}

//returns a new Rational object that contains the reciprocal of the object that
//invoked the method
//Method #1
public Rational reciprocal(){
    this(rat1.getDenom(), rat1.getNumer()); 
}

//Method #2
public Rational reciprocal(Rational dup){
    this(dup.getDenom(), dup.getNumer());   
}

我想用对象rat1调用倒数方法,但是我无法弄清楚如何在方法中引用rat1的变量。有没有办法以类似于方法#1的方式执行此操作。 (顺便说一下,我意识到这不起作用)另外,当使用方法#2时,为什么我一直得到一个"构造函数调用必须是第一个语句"错误,即使它是第一行?

1 个答案:

答案 0 :(得分:2)

我们不清楚rat1方法中<{1}}对 的含义......但您不能使用{reciprocal {1}}这些是方法,而不是构造函数。它看起来像你可能想要的那样:

this(...)

如果您想要调用这些方法,您可以在public Rational reciprocal() { return new Rational(denom, numer); } 隐式执行这些方法:

this

或者您可以明确使用public Rational reciprocal() { return new Rational(getDenom(), getNumer()); }

this

...但您的第二个public Rational reciprocal() { return new Rational(this.getDenom(), this.getNumer()); } 方法没有意义,因为您只需拨打reciprocal而不是x.reciprocal()

作为旁注,我重命名方法和变量以避免缩写:

irrelevantRational.reciprocal(x)

如果我是你,我也会成为班级private int numerator, denominator; public int getNumerator() { return numerator; } // etc 并且不可改变。