Java – uses an object as a variable in the constructor
•
Java
I have a question about using objects as variables in constructors It may be simple, but I really can't think of what to do. My java book doesn't really help Said I wanted to
Fraction f3 = new Fraction(1,2); Fraction f5 = new Fraction(f3);
The constructor of my first object is:
public Fraction(int n,int d) { if (d == 0) { numerator = 0; denominator = 1; System.err.println("Error: Invalid Denominator (" + d + ")"); } else if (d < 0) { int nn = Math.abs(n) * (-1); numerator = nn; denominator = Math.abs(d); } else { numerator = n; denominator = d; } }
The constructor of my second object is like this:
public Fraction(Fraction f) { }
I can't figure out how to define a constructor to set a new object to a given object I would appreciate it if someone could give me a hand or some suggestions to solve it
Solution
public Fraction(Fraction f){
public Fraction(Fraction f){ this(f.numerator,f.denominator); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码