Constructor basics
- Java course
- Intermediate
- Lesson 7/116
- 5 min
Learn the class constructor method.
Constructor basics
A constructor lets an instance receive initial values when it is created. The constructor's name matches the class name, it has no return type and it is called with new. A constructor assigns starting values to fields.
Example: class Point { int x; Point() { x = 0; } }. Here Point() is a constructor. When new Point() is called, this constructor runs and assigns zero to x. A constructor does not use return; no return type is written. Its name must exactly match the class name.
Constructor invocation
A constructor is called with the new keyword. The call creates a new instance in memory and runs the constructor body. When the body finishes, the instance is ready to use.
Example: Point p = new Point();. Here new Point() calls the Point constructor. The body runs x = 0; and p.x becomes zero. If no constructor is defined, Java adds an empty one automatically; that is why new Point() always works.
Practice Add a constructor to the Point class
Define a class named Point. Add int x and int y fields. Write a no-argument constructor; its body assigns zero to both x and y. In main create a Point instance and print x and y on separate lines.
Starter code
// Define the Point class
// Add a constructor
// Instantiate and print in mainSample solution
class Point {
int x;
int y;
Point() {
x = 0;
y = 0;
}
public static void main(String[] args) {
Point p = new Point();
System.out.println(p.x);
System.out.println(p.y);
}
}Expected output
0 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a constructor definition?
- Point() { } Correct answer
- void Point() { }
- constructor Point() { }
- def Point(): pass
Explanation: A constructor's name matches the class name and has no return type.
2 Complete the constructor definition
class Point {
int x;
____ {
x = 0;
}
}
class Point {
int x;
Point {
x = 0;
}
}
Explanation: The constructor name must match the class name.
3 Match the constructor parts
| Term | Meaning |
|---|---|
Point |
Constructor name |
() |
Parameter list |
{ } |
Body |
new |
Call keyword |