Concept
How can constructors call one another and copy objects?
ComputerScienceOne / Constructors
"In both of these examples, we repeated a lot of code. One shortcut is to make all your constructors call the most general constructor. To invoke another constructor, we use the this keyword as a method call. For example:\n\n1 public Student() {\n\n2 this(null, null, 0, 0.0);\n\n3 }\n\n4\n\n5 public Student(String firstName, String lastName) {\n\n6 this(firstName, lastName, 0, 0.0);\n\n7 }\n\nAnother, very useful type of constructor is the copy constructor that allows you to make a copy of an instance by passing it to a constructor. The following example copies each of the member variables of s into this.\n\n1 public Student(Student s) {\n\n2 this(s.firstName, s.lastName, s.id, s.gpa);\n\n3 }"
Related Ideas
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- What is a constructor and how is it written?ComputerScienceOne · Constructors
- How should a class manage owned collections and avoid shallow copies?ComputerScienceOne · Composition
- How can you create a deep copy of a Student structure?ComputerScienceOne · To String Functions
- How should a copied structure avoid sharing references?ComputerScienceOne · Factory Functions
- How are Java class instances created and used?ComputerScienceOne · Common Methods
- How do you declare and instantiate Java class instances?ComputerScienceOne · Usage
- How can strings be copied and their characters accessed in Java?ComputerScienceOne · Basics