Methods
Apex Instance Methods
Instance Methods
Apex instance methods operate on class instances.
What are Instance Methods in Apex?
Instance methods in Apex are functions that belong to an instance of a class. Unlike static methods, which are called on the class itself, instance methods require you to create an object of the class before you can invoke them. These methods typically operate on the data contained within the instance and can access the instance's properties and other methods.
Defining an Instance Method
To define an instance method in an Apex class, you do not use the static
keyword. Instead, you define it like a regular method, and it automatically becomes an instance method. Here is an example:
Creating and Using an Instance
To use instance methods, you must first create an instance of the class. You can then call the instance methods on this object. Here's how you can create an instance of the Calculator
class and use its methods:
Benefits of Using Instance Methods
Instance methods are beneficial when you need to perform operations that depend on the instance's state. They allow encapsulation and provide a way to manage data specific to an instance. This approach is suitable for scenarios where data needs to be maintained separately for different objects of the same class.
Comparing Instance and Static Methods
While both instance and static methods are used in Apex, they serve different purposes. Instance methods operate on specific class instances, allowing you to manipulate instance-specific data. In contrast, static methods can be called without creating an instance and usually operate on data that is shared across all instances of the class.
Choose instance methods when operations need to be tied to a particular object, and select static methods when you need functionality that doesn't depend on instance variables.
Methods
- Methods
- Static Methods
- Instance Methods
- Virtual Methods
- Previous
- Static Methods
- Next
- Virtual Methods