In Apex, the Object data type is a generic data type that can be used to represent any type of data,
including custom and standard objects, sObjects, and even primitive data types such as integers, strings,
and more. It's a versatile data type that can store various types of data,
making it useful in situations where you want to work with data in a flexible and dynamic way.
public class ObjectExample {
public static void main() {
// Declare variables of type Object
Object data;
// Assign different types of data to the Object variables
data = 42; // Assign an integer
System.debug('Data (Integer): ' + data);
data = 'Hello, World'; // Assign a string
System.debug('Data (String): ' + data);
// Create a custom object and assign it to an Object variable
MyCustomObject__c customObject = new MyCustomObject__c();
customObject.Name = 'Custom Record';
data = customObject;
System.debug('Data (Custom Object): ' + data);
}
}
We declare an Object variable data without specifying its type. This allows us to store different types of data in it.
We assign an integer value, a string, and a custom object to the data variable at different points in the program.
We use System.debug() to print the value of data at each step.
The Object data type is versatile and allows you to work with a wide range of data, but it has limitations. When working with data stored in an Object variable, you need to perform type casting to access specific methods or properties associated with the actual data type you expect. Using Object can make your code more flexible,