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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. 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 new and never called again on an existing object. Writing a return type, even void, would make it a plain method.

  • What are p.x and p.y after p is created?

    ```java
    class Point {
    int x;
    int y;
    Point(int x) {
    this.x = x;
    }
    }

    Point p = new Point(3);
    `

    • 3 and 0
    • 3 and 3
    • 0 and 0
    • 3 and null
    Show the answer

    3 and 0

    The constructor only assigns this.x. y is an int: it keeps the default value 0, never null (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 only Point(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.