Why does this getter method return zero?

advertisements

So, as the title suggests, I have created an object passed it certain parameters. No matter what, the value is reset back to zero.

Here is the class

public class Rational {
private int numerator;
private int denominator;    

public int getNumerator() {
    return numerator;
}
public void setNumerator(int numerator) {
    this.numerator = numerator;
}
public int getDenominator() {
    return denominator;
}
public void setDenominator(int denominator) {
    this.denominator = denominator;
}

Rational(int numerator, int denominator)
{   

if (this.denominator < 0)
    {
        this.denominator = denominator * -1;
        this.numerator = numerator * -1;
    }

    if (denominator == 0)
    {
        this.denominator = 1;
        this.numerator = 0;
    }

}

Here is main

public class User {

public static void main(String[] args) {

    Rational r1 = new Rational(1,6);
    //Rational r2 = new Rational(-5, -7);
    System.out.println(r1.getDenominator()); //THIS PRINTS OUT 0
}

}

Why does the println print a zero?


Your constructor sets no fields whatsoever.

You must set the this.numerator and this.denominator for it to change the state of these fields.

e.g., in the constructor you never do

this. numerator = something;
this.denomintor = someOtherThing;