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.
new
// 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?
new Student("Ada", 90)
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.
this
True or false?