Search code examples
javathis

Why can't I set "this" equal to an object in a constructor?


I have a constructor in an object class that passes its input values to a function that returns an object of the same type and I was wondering why I can't set all the instance variables for the new object in one line, like this: this = function(); Here's my current solution:

public class Fraction {
    long num;
    long den;

    public Fraction(double numIn, double denIn){
        Fraction temp = reduceFraction(numIn, denIn);
        num = temp.num;
        den = temp.den;
    }

I can also do this:

    public Fraction(double numIn, double denIn){
        Fraction temp = reduceFraction(numIn, denIn);
        this.num = temp.num;
        this.den = temp.den;
    }

Something like this would be a lot cleaner, but doesn't work:

    public Fraction(double numIn, double denIn){
        this = reduceFraction(numIn, denIn);
    }

Since my object only has two instance variables, it's not that big of a deal to set each individually, but it seems like that would be really inconvenient with more complex objects. Is there another way I could accomplish this that's cleaner than my current solution?


Solution

  • You simply cannot deference an instance within itself.

    Why not make reduce function assign the local instance variables itself, assuming it's not a public static method?

    If it were a public static method, you would just do

    Fraction f = Fraction.reduceFraction(numIn, denIn); rather than Fraction f = new Fraction(numIn, denIn)

    And in the reduce method, I assume you've done return new Fraction(numIn, denIn)? If so, I think you'd have a recursive constructor loop