简体   繁体   English

使用对象作为构造函数的变量

[英]Using an object as a variable for a constructor

I have a question about using an object as the variable in a constructor. 我有一个关于在构造函数中使用对象作为变量的问题。 It might be simple but I just really can't think of what to do and my java book isn't really helping. 它可能很简单,但我真的想不出该怎么做,我的java书并没有真正帮助。 Say i wanted to do this 说我想这样做

Fraction f3 = new Fraction(1, 2);
Fraction f5 = new Fraction(f3);

my constructor for the 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;
    }

}

my constructor for the second object is this: 我的第二个对象的构造函数是这样的:

public Fraction(Fraction f) 

{

}

I can't think of how to define the constructor to get it to set a new object as the object given. 我想不出如何定义构造函数以使其将新对象设置为给定的对象。 If anyone could give me a hand or maybe some advice to put me on the path to figuring it out I would greatly appreciate it. 如果有人能给我一个手或者一些建议让我走上解决它的道路,我将非常感激。

public Fraction(Fraction f){
  this(f.numerator, f.denominator);
}

I would use "constructor chaining" to ensure the changes made to one are reflected in the other. 我会使用“构造函数链接”来确保对一个进行的更改反映在另一个中。

// copy constructor
public Fraction(Fraction f) {
    this(f.numerator, f.denominator); // call the regular constructor with f's params
}
public Fraction(Fraction f){
  this.n = f.n;
  this.d = f.d;
}

Do you want something such that 你想要这样的东西吗?

Fraction a = .... ;
Fraction b = new Fraction(a);
System.out.println(a==b);

prints true ? 打印true吗? That is not possible in Java; 这在Java中是不可能的; new always produces a fresh object that is separate from all previously existing objects. new始终生成一个与所有先前存在的对象分开的新对象。

(This is in contrast to, say, ECMAScript, where a constructor is allowed to return an existing object and discard the fresh object the runtime created and passed as the constructor's this ). (这是相反的,比方说,ECMAScript中,其中一个构造函数允许返回现有对象并丢弃新鲜的对象创建和传递的运行构造的this )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM