Object data type
Object data type
The Object data type in Apex is a generic or base type that can hold any data type,
whether it's a primitive type, collection, custom object, or standard object. It’s like a
catch-all container that can store any kind of value or reference.
Generic Type:
Implicit Casting:
1. Apex automatically casts specific types to Object. When you assign a value to an
Object type variable, Apex will implicitly convert it to Object.
2. E
Type Casting:
1. When you retrieve a value from an Object variable and need to use it as a specific
type, you must explicitly cast it back to its original type.
2. E
Flexibility:
1. Since Object can hold any type, it's useful for handling dynamic or unknown data
types. For example, if you’re writing generic methods that should work with
multiple types, you can use Object as the input parameter.
// Output values
System.debug('Stored String: ' + objString);
System.debug('Stored Integer: ' + objInteger);
System.debug('Stored Boolean: ' + objBoolean);
System.debug('Stored Date: ' + objDate);
System.debug('After casting: String = ' + str + ', Integer = ' + num + ',
Boolean = ' + flag + ', Date = ' + today);
}
}
Generic Method: You can write methods that can accept any type of
parameter by using Object as the parameter type. This makes the method
flexible for multiple use cases.
Example:
System.debug('Name: ' + name + ', Age: ' + age + ', Active: ' + isActive);
Generic code: When writing flexible or reusable methods, Object allows you to accept and
work with any type.
Dynamic data handling: When working with APIs, integrations, or scenarios where the data
types are not fixed in advance.