ApexSensei

Drills › Think in classes

Initialize an appointment plan

Think in classes · Beginner · 12 min · Runs in your Salesforce Developer org · Free

Scenario. A scheduler must create complete appointment plans and never allow a plan that is too short to be useful.

Use a constructor to set up an appointment plan and enforce a minimum length.

What you will learn

A constructor runs when new creates an object. It has the class name and no return type. Use it to give every new object a valid starting state.

public Ticket(String subject) {
    this.subject = subject;
}

this.subject is the field. Plain subject is the parameter.

Gotcha. Parameters do not fill fields by themselves. You must assign them.

The task

Finish the AppointmentPlan constructor so it stores the customer name and length, with a 15-minute minimum.

Examples:

  • new AppointmentPlan('Acme onboarding', 45) → Standard: Acme onboarding :: 45 min
  • new AppointmentPlan('Data review', 30) → Half-hour: Data review :: 30 min
  • new AppointmentPlan('Quick check', 0) → Zero minutes: Quick check :: 15 min

Requirements:

  1. In the constructor, copy both parameters into the object's fields.
  2. If the length is under 15 minutes, store 15 instead.
  3. Create one plan for each example. Print Standard:, Half-hour: and Zero minutes:, each followed by its summary().
  4. The checks also create plans with other names and lengths, so the rule must work for any input.

Starter code

class AppointmentPlan {
    public String customerName;
    public Integer durationMinutes;

    public AppointmentPlan(String customerName, Integer durationMinutes) {
    }

    public String summary() {
        return customerName + ' :: ' + durationMinutes + ' min';
    }
}

AppointmentPlan standard = new AppointmentPlan('Acme onboarding', 45);
System.debug('Standard: ' + standard.summary());

When it passes

Each constructor call sets up its own plan, and any length under 15 minutes becomes 15.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Return a value and record work · Protect a support ticket subject ›