-1

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?

Frostbiyt
  • 23
  • 5
  • Use a static factory method if you want control over new instances. – shmosel Feb 26 '22 at 01:19
  • It just doesn't work that way. No reason it should given that there are a number of valid ways to do what you want without creating an extra `Function` object. OneCricketeer's answer is a good one. @shmosel's comment is even better. In this case, I'd add a static factory method to `Function` that returns the result of calling `reduceFraction` – CryptoFool Feb 26 '22 at 01:27

1 Answers1

1

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245