Constructors
Skill 2.BSkill 3.B
Big idea: A constructor gives a brand-new object its starting state. Any instance variable it doesn't set keeps its default value.
- Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class.
Setting the initial state
An object's state is its attributes and their current values. The constructor's job is to give every instance variable a sensible value, usually from its parameters.
Instance variables you don't assign get defaults: 0 for int, 0.0 for double, false for boolean, and null for references.
public class Student {
private String name;
private int grade;
private boolean active;
public Student(String n) {
name = n;
// grade and active get default values: 0 and false
}
public Student(String n, int g) {
name = n;
grade = g;
active = true;
}
public String toString() {
return name + " " + grade + " " + active;
}
}Overloaded constructors and defaults
CodeStudent a = new Student("Mo");
Student b = new Student("Ivy", 11);
System.out.println(a);
System.out.println(b);OutputMo 0 false Ivy 11 true
The default constructor
If you write no constructor at all, Java provides a no-parameter one that leaves every instance variable at its default. Once you write any constructor, that free one disappears.
CodeItem it = new Item();
System.out.println(it.getQty() + " " + it.getName());Output0 nullThe local-variable trap
Writing a type in front of a name inside the constructor declares a new local variable. The instance variable is left at its default.
CodeBox b = new Box(5);
System.out.println(b.getSize());Output0- A constructor sets the initial state, giving every instance variable a value.
- Instance variables form a has-a relationship (a Student has a name).
- Defaults:
int0,double0.0,booleanfalse, referencesnull. - With no constructor written, Java supplies a no-parameter default constructor.
- When given a mutable object, a constructor should store a copy so outside code can't change the object's state.
- A constructor has no return type, not even
void.public void Box()is a method, not a constructor. int size = s;in a constructor creates a local variable and leaves the instance variable at 0.
Is public Cube(int side) a valid constructor for class Cube? What about public void Cube()?
Show answer
The first is. The second has a return type, so it is an ordinary method named Cube.