Constructors
Initialising an object's state when it is created: default constructor, parameterised and overloaded constructors, this(…) calls, attribute default values and copy constructors, in Java.
- 24 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Understand
A few cards from the deck
Constructor: what is it?
Show the answer
A block of code, named after the class and with no return type, run each time an object is created to initialise its state.
It is called with
newand never called again on an existing object. Writing a return type, evenvoid, would make it a plain method.What are
p.xandp.yafterpis created?
```java
class Point {
int x;
int y;
Point(int x) {
this.x = x;
}
}
Point p = new Point(3);`3and03and30and03andnull
Show the answer
3and0The constructor only assigns
this.x.yis anint: it keeps the default value 0, nevernull(reserved for references).A constructor has the same name as the … and declares no …, not even void.
Show the answer
A constructor has the same name as the class and declares no return type, not even void.
public void Point(int x)compiles, but it is an ordinary method that happens to be called Point:new Point(3)does not call it.Default constructor: what is it?
Show the answer
The parameterless constructor that the compiler adds by itself, only when the class declares none.
As soon as you write a constructor it disappears:
new Point()no longer compiles if onlyPoint(int x)exists.Why write a constructor rather than assign the attributes one by one after the
new?- Attributes can only be assigned inside a constructor
- Without a constructor, the class cannot be instantiated
- The constructor runs faster than an assignment
- No object exists without first receiving a coherent starting state
Show the answer
No object exists without first receiving a coherent starting state
The constructor guarantees the initialisation happens, once, before any other use. Without it, an attribute could be forgotten. A class with no constructor can still be instantiated thanks to the default constructor.