Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor isn't printing as expected

Tags:

java

public class Fraction
{
    public Franction(int n, int d)
    {
        int num = n;
        int denom = d;
    }

    public static void main(String[] args)
    {
        Fraction f1 = new Fraction(5,10);
        System.out.println("Fraction = " + f1);
    }
}

Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction@33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!

like image 654
user2739123 Avatar asked Feb 22 '26 01:02

user2739123


1 Answers

To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName@hashCode.

Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.

Try something like this:

public class Fraction
{
    private final int num
    private final int denom;

    public Franction(int n, int d)
    {
        this.num = n;
        this.denom = d;
    }

    @Override
    String toString() 
    {
        return String.format("%d/%d", num, denom);
    }

    public static void main(String[] args)
    {
        Fraction f1 = new Fraction(5,10);
        System.out.println("Fraction = " + f1);
    }
}
like image 184
Marcin Łoś Avatar answered Feb 23 '26 15:02

Marcin Łoś