Properties: get and set
By the end of this lesson, you'll be able to:
- Write a property with custom get and set logic
- Explain why a property can be safer than a plain public field
- Use a property to validate data on assignment
Prerequisites: "Static vs Instance Members"
A plain field has no protection
public class EventTicket {
public Decimal price;
}
EventTicket ticket = new EventTicket();
ticket.price = -500; // perfectly legal, but nonsensical
Nothing stops a plain public field from being set to a value that makes no business sense. A negative ticket price shouldn't be allowed, but a plain field has no way to say so.
A property with validation in set
public class EventTicket {
public Decimal price {
get { return price; }
set {
if (value < 0) {
price = 0;
} else {
price = value;
}
}
}
}
EventTicket ticket = new EventTicket();
ticket.price = -500;
System.debug(ticket.price); // 0, not -500
The syntax ticket.price = -500 looks identical to setting a plain field, but it now runs through the set block, where value is the incoming value being assigned. Invalid input gets corrected before it's ever stored.
Auto-properties: the shorthand
public class EventTicket {
public String eventName { get; set; }
}
When you don't need custom logic, { get; set; } is shorthand for a plain property with default get/set behavior — functionally similar to a public field, but written in a way that leaves room to add real validation later without changing how callers use it.
Exercise
Write a property called pageCount on a class Book that rejects negative values by storing 0 instead.
Show hint
set { if (value < 0) { pageCount = 0; } else { pageCount = value; } }
Properties: get and set Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A property looks like a plain field from the outside but can run real logic behind the scenes when read (get) or written (set) — most commonly used to validate or transform data.