Concept
How does Java handle default and multiple constructors?
ComputerScienceOne / Constructors
"Java allows us to define multiple constructors, or even no constructor at all. If we do not specify a constructor, Java provides a default, no argument constructor. This constructor uses default values for all member variables (zero for numerical types, false for boolean types, and null for objects). If we do specify a constructor, this default constructor becomes unavailable. However, we can always “restore” it by explicitly defining it.\n\n1 public Student() {\n\n2 this.firstName = null;\n\n3 this.lastName = null;\n\n4 this.id = 0;\n\n5 this.gpa = 0.0;\n\n6 }\n\nAlternatively, we can define constructors that accept a subset of variable values.\n\n1 public Student(String firstName, String lastName) {\n\n2 this.firstName = firstName;\n\n3 this.lastName = lastName;\n\n4 this.id = 0;\n\n5 this.gpa = 0.0;\n\n6 }"
Related Ideas
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- How can PHP default values let a constructor accept different numbers of parameters?ComputerScienceOne · Usage
- How does a constructor initialize a PHP object?ComputerScienceOne · Constructors
- How do you declare and instantiate Java class instances?ComputerScienceOne · Usage
- How are Java class instances created and used?ComputerScienceOne · Common Methods
- What shorthand and read-only options are available for Java variables?ComputerScienceOne · Declaration & Assignment
- How do you create a custom exception in Java?ComputerScienceOne · Creating Custom Exceptions
- How should a class manage owned collections and avoid shallow copies?ComputerScienceOne · Composition