Creating Your First Class
By the end of this lesson, you'll be able to:
- Write a complete class with fields and a method together
- Call a method on a specific object using dot notation
- Explain how a method inside a class can use that object's own fields
Prerequisites: "What Is an Object?"
Fields and methods together
public class EventTicket {
public String eventName;
public Decimal price;
public String describe() {
return eventName + ' — R' + price;
}
}
EventTicket ticket = new EventTicket();
ticket.eventName = 'Summer Music Festival';
ticket.price = 350;
System.debug(ticket.describe()); // "Summer Music Festival — R350"
Inside describe(), eventName and price refer to that specific object's values — the same method, called on a different EventTicket object, would use that object's own data instead.
A real business example: Event Management
EventTicket vipTicket = new EventTicket();
vipTicket.eventName = 'Tech Conference';
vipTicket.price = 1200;
EventTicket generalTicket = new EventTicket();
generalTicket.eventName = 'Tech Conference';
generalTicket.price = 450;
System.debug(vipTicket.describe()); // "Tech Conference — R1200"
System.debug(generalTicket.describe()); // "Tech Conference — R450"
One describe() method, reused by every ticket object — each call naturally reflects that specific ticket's own price, because the method reads its own object's fields.
Exercise
Write a class named Book with fields title (String) and pageCount (Integer), and a method summary() that returns a String combining both. Create one object and debug its summary.
Show hint
return title + ' has ' + pageCount + ' pages';
Creating Your First Class 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
Classes combine data (fields) and behavior (methods) in one place — this lesson writes a complete class where a method uses the object's own field values.