我正在为入门级java做一些功课,我跑到了这里。我不知道它让我做了什么。这只是设置“Date
”等于"Date d"
中的值吗?还是我错过了什么?我不觉得那么长的解释会被用于一行代码。
有人可以解释一下这里发生了什么以及我错过了什么吗?
复制构造函数:这是一个接受一个参数的构造函数 键入Date,然后设置接收(或执行)对象实例 变量等于参数对象的变量。结果是 接收对象是形式参数对象的副本:
public Date( Date d )
答案 0 :(得分:0)
您需要做的就是获取d的所有字段并将其复制到新日期。因此,如果日期有时间,一天,一个月和一年,请将所有这些复制到新日期。就是这样。
答案 1 :(得分:0)
class Complex {
private double re, im;
// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
// Overriding the toString of Object class
@Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
// Following involves a copy constructor call
Complex c2 = new Complex(c1);
// Note that following doesn't involve a copy constructor call as
// non-primitive variables are just references.
Complex c3 = c2;
System.out.println(c2); // toString() of c2 is called here
}
}