1af7b5c1ea96413f871aabc81b02a8e8 by Unknown

1af7b5c1ea96413f871aabc81b02a8e8 by Unknown

Author:Unknown
Language: eng
Format: epub


–

A static method belongs to the class itself, not to instances of the class.

–

It can be called using the class name, without creating an instance of the class.

–

Static methods cannot access instance variables, but they can access other static variables or other static methods.

101

Chapter 5 Data Manipulation language (DMl) Let’s say you have a class called StringUtil that contains a static method called capitalizeFirstLetter. This method takes a string as input and returns the string with the first letter capitalized. Here’s how the code would look:

Step 1: Create the class

public class StringUtil {

public static String capitalizeFirstLetter(String input) {

if (String.isBlank(input)) {

return input;

}

return input.substring(0, 1).toUpperCase() + input.substring(1);

}

}

Step 2: Save the class

Step 3: Open the anonymous window

Step 4: Test the public class

// Example usage in the Anonymous Apex window

String inputString = 'hello';

String capitalizedString = StringUtil.capitalizeFirstLetter(inputString); System.debug('Original String: ' + inputString);

System.debug('Capitalized String: ' + capitalizedString); To use this static method, you can call it directly on the class name, without creating an instance of the StringUtil class. The provided Apex code above capitalizes the first letter of a given string using a static method in the StringUtil class.

This is just one example of how you can use Apex static methods. They are flexible and can be used in various scenarios to perform specific tasks without the need to create an instance of the class.

Virtual Methods

In Apex, a virtual method is a method declared in a base class that can be overridden in its subclasses. This allows you to provide different implementations of the method in different subclasses. This concept is useful when you want to define a common behavior in a base class, but allow its subclasses to customize or extend that behavior.

102

Chapter 5 Data Manipulation language (DMl) In the given example, we start with a base class named Item, which defines a virtual method called calculateProperty(). The intention is to create specialized subclasses, such as Car and Bicycle, each offering its own unique implementation of the calculateProperty() method.

public class Item {

public virtual void calculateProperty() {

System.debug('Calculating some property of the item');

}

}

public class Car extends Item {

private Decimal fuelEfficiency;

public Car(Decimal fuelEfficiency) {

this.fuelEfficiency = fuelEfficiency;

}



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.