0
我创建了一个名为Rational的类,它存储两个私有整数(数字和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,为什么我一直得到“构造函数调用必须是第一个语句”错误,即使它是第一行?
用途:'return new Retional(getDenom(),getNumer());'? –