繁体   English   中英

如何在调用的方法内引用对象?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM