Hello,
I feel embarrassed to ask these types of questions but i can't get answers to them in my text book. So here you go:
I have an assignment of copying the constructor writing clone() method and add() method. While i understand the idea of creating of clone and add methods i am having difficulty understanding why do we need to copy a constructor? And also, where do we copy it to? Should i create a separate class to copy the constructor or should i do it in the same class?

Thank you

Recommended Answers

All 3 Replies

One class can only have one constructor with any given list of parameters (although it can have any number of constructors that take different parameters). So it makes no sense to copy a constructor in the same class. If you create a subclass, the superclasses' constructors are NOT inherited, so you need to create new constructors for the subclass. In that case you MAY start by copying the superclasses' constructors, although the normal practice would be to write a small constructor that just calls a superclass constructor as required.

I think the OP is talking about the "copy constructor" like functionality which exists in C++ and can be implemented in Java by:
- implementing the Cloneable interface
- overriding the clone() method of the Object class

@grisha83

Read the documentation of the clone() method of the Object class and this for more details.

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.