[英]How do i refer to an object inside a method that it has invoked?
我創建了一個名為Rational的類,該類存儲了兩個私有的int(數字和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時,為什么即使它是第一行,也總是收到“構造函數調用必須是第一條語句”錯誤?
目前還不清楚是什么rat1
,就是要在你的reciprocal
方法......但原因你不能只用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()
而不是x.reciprocal()
irrelevantRational.reciprocal(x)
。
附帶說明一下,我將方法和變量都重命名以避免縮寫:
private int numerator, denominator;
public int getNumerator() {
return numerator;
}
// etc
如果我是你的話,我也要使這堂課final
變得一成不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.