سؤال

I need to have a copy constructor in my class as i need to create duplicate objects. I believe that if i will create a copy constructor, I will have to specify the non parameterized constructor too as Java will no longer provide the default constructor.

I don't want to touch the default constructor as that is what i being used in the code everywhere. Is there a workaround to have either a copy constructor or something like it without defining the basic constructor.

هل كانت مفيدة؟

المحلول

No, if you want to have both a parameterless constructor and a constructor with parameters, you need to declare them both. It's very easy to declare the parameterless constructor though:

public YourClassName() {
}

The super(); is implicit.

That will behave exactly the same way as the default constructor would, although it won't necessarily have the same access as the default constructor. (You can change it from being public if you want, of course.) From the JLS section 8.8.9:

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor (§6.6) that takes no arguments and has no throws clause.

In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

نصائح أخرى

If you really do not want to write the default constructor, you can do:

public static MyClass create(MyClass original) {
    // return the new instance
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top