2016-12-26 80 views
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,为什么我一直得到“构造函数调用必须是第一个语句”错误,即使它是第一行?

+0

用途:'return new Retional(getDenom(),getNumer());'? –

回答

2

目前还不清楚是什么rat1reciprocal方法是指 ...但你不能只使用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 

我还使课堂final的和不可改变的,如果我是你。