Sub topic 1
Declaring an Apex Class
Prerequisites
Assume you know basic Apex syntax, collections such as List and Map, transactions, and the idea that objects have state and methods.
Declaring an Apex class
A class is a blueprint for objects. It groups data in variables and actions in methods.
public class Counter {
private Integer count;
public Counter() {
this(0);
}
public Counter(Integer startAt) {
this.count = startAt;
}
public void increment() {
count++;
}
public Integer getCount() {
return count;
}
}The class keyword declares the type. Counter is the class name. Each object created with new Counter() has its own count.
Controlling visibility with access modifiers
An access modifier controls which code can use a class member.
privateallows access only inside the declaring class.protectedallows access inside the class and its subclasses.publicexposes a member within the application namespace.globalexposes a member to code outside the namespace, such as subscribers to a managed package.
Use the narrowest visibility that meets the requirement. A private field with a public method is common because the class controls how callers change its state.
Instance variables and methods: state per object
An instance variable belongs to one object. An instance method can read or change that object's variables. The a and b objects below do not share count.
Counter a = new Counter();
Counter b = new Counter(5);
a.increment();
System.debug(a.getCount()); // 1
System.debug(b.getCount()); // 5This separation lets one class represent many independent values.
Constructors, chaining, and this
A constructor initializes a new object. Its name matches the class and it has no return type. this refers to the current object. Constructor chaining with this(0) calls another constructor and must be the first statement.
Static variables and methods: state per class
A static member belongs to the class, not to an individual object. Access it through the class name. Static methods cannot directly use instance variables because they have no current object.
public class Counter {
public static Integer instancesCreated = 0;
public Counter() {
instancesCreated++;
}
public static Integer getCreatedCount() {
return instancesCreated;
}
}Use static members for class-wide behavior or shared transaction state. Use instance members when each object needs separate state.
Exercise
Which construct should you use when two Counter objects must keep different counts?
Show answer
Use an instance variable, because each object receives its own copy of that state.