Java 如何引用已调用的方法中的对象?
我创建了一个名为Rational的类,它存储两个私有int(numer和denom)。我试图创建一个方法,该方法返回一个新的Rational对象,该对象包含调用该方法的对象的倒数Java 如何引用已调用的方法中的对象?,java,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; thi
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时,为什么即使是第一行,我仍会收到“构造函数调用必须是第一个语句”错误?不清楚
rat1
在倒数方法中意味着什么。。。但是不能只使用this(…)
的原因是这些是方法,而不是构造函数。在我看来,你可能想要:
public Rational reciprocal() {
return new Rational(denom, numer);
}
如果您想调用这些方法,可以在this
上隐式调用它们:
public Rational reciprocal() {
return new Rational(getDenom(), getNumer());
}
或者您可以显式地使用此
:
public Rational reciprocal() {
return new Rational(this.getDenom(), this.getNumer());
}
。。。但是您的第二个互惠
方法没有意义,因为您可以直接调用x.interactive()
而不是无关的.interactive(x)
作为旁注,我将重命名方法和变量以避免缩写:
private int numerator, denominator;
public int getNumerator() {
return numerator;
}
// etc
如果我是你的话,我也会让类成为最终的
和不可变的。不清楚rat1
在你的交互
方法中意味着什么。。。但是不能只使用this(…)
的原因是这些是方法,而不是构造函数。在我看来,你可能想要:
public Rational reciprocal() {
return new Rational(denom, numer);
}
如果您想调用这些方法,可以在this
上隐式调用它们:
public Rational reciprocal() {
return new Rational(getDenom(), getNumer());
}
或者您可以显式地使用此
:
public Rational reciprocal() {
return new Rational(this.getDenom(), this.getNumer());
}
。。。但是您的第二个互惠
方法没有意义,因为您可以直接调用x.interactive()
而不是无关的.interactive(x)
作为旁注,我将重命名方法和变量以避免缩写:
private int numerator, denominator;
public int getNumerator() {
return numerator;
}
// etc
如果我是你,我也会使类final
不可变。使用:returnnewretional(getDenom(),getNumer())代码>?使用:返回新的Retional(getDenom(),getNumer())代码>?