Bifalgorithm post · Computer science one · Constructors

How can constructors call one another and copy objects?

How can constructors call one another and copy objects? (Computer science one · Constructors) — "In both of these examples, we repeated a lot of code. One shor…

Ideas in this flowchart

  • Constructor reuse and copy constructors reduce repeated code.
  • The examples contain a lot of repeated code.
  • A shortcut is to make constructors call the most general constructor.
  • The this keyword invokes another constructor as a method call.
  • The no-argument Student constructor delegates with this(null, null, 0, 0.0).
  • The two-argument Student constructor delegates with this(firstName, lastName, 0, 0.0).
  • A copy constructor creates a copy of an instance passed to it.
  • The copy constructor receives a Student instance as its parameter.
  • It copies each member variable of s into this.
Feed/

How can constructors call one another and copy objects?

No cover

Channel

Computer science one

1 page

"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 }"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.