How do i refer to an object inside a method that it has invoked?

I've created a class named Rational which stores two private ints (numer and denom). I am trying to create a method that returns a new Rational object that contains the reciprocal of the object that invokes the method.

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());   
}

I want to invoke the reciprocal method with object rat1, but I can't figure out how to reference rat1's variables inside of the method. Is there any way to do this in a similar style to Method #1. (btw I'm aware that this does not work) Also, when using Method #2, why do I keep getting a "constructor call must be the first statement" error even though it is the first line?

Jon Skeet
people
quotationmark

It's not clear what rat1 is meant to be in your reciprocal method... but the reason you can't just use this(...) is that these are methods, not constructors. It looks to me like you probably want:

public Rational reciprocal() {
    return new Rational(denom, numer);
}

If you want to call the methods instead, you could either just do them implicitly on this:

public Rational reciprocal() {
    return new Rational(getDenom(), getNumer());
}

Or you could use this explicitly:

public Rational reciprocal() {
    return new Rational(this.getDenom(), this.getNumer());
}

... but there's no point in your second reciprocal method because you could just call x.reciprocal() instead of irrelevantRational.reciprocal(x).

As a side note, I'd rename both the methods and variables to avoid abbreviation:

private int numerator, denominator;

public int getNumerator() {
    return numerator;
}

// etc

I'd also make the class final and immutable, if I were you.

people

See more on this question at Stackoverflow