Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.2 Constructors — building objects

Lesson

Different objects, different starting values

A constructor with parameters lets each new build an object with its own starting state. Passing different arguments creates objects that differ from the moment they exist — no need to set each field by hand afterwards.


Worked example

// Dog(String n, int a) sets name and age
Dog a = new Dog("Rex", 3);
Dog b = new Dog("Fido", 5);
System.out.println(a.name + " " + a.age);   // Rex 3
System.out.println(b.name + " " + b.age);   // Fido 5

▶ Try it: two dogs, each built with its own values. Run this, then change the arguments and re-run.



What does new Student("Ada", 90) do, if the constructor takes a name and a grade?


Type exactly what this program prints.

class Student {
    String name;
    int grade;

    Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Ada", 90);
        System.out.println(s.name + " " + s.grade);
    }
}

Order the lines of a constructor that sets both fields using this.


True or false?