PDI · Question #24
A developer is implementing an Apex class for a financial system. Within the class, the variables creditAmount' and debtAmount' should not be able to change once a value is assigned. In which two…
The correct answer is B. Use the final keyword and assign its value in the class constructor. D. Use the final keyword and assign its value when declaring the variable. To ensure an Apex variable is assigned a value only once and remains constant, it must be declared with the final keyword, with assignment occurring either at declaration or within the class constructor.
Question
A developer is implementing an Apex class for a financial system. Within the class, the variables creditAmount' and debtAmount' should not be able to change once a value is assigned. In which two ways can the developer declare the variables to ensure their value can only be assigned one time? Choose 2 answers
Options
- AUse the static keyword and assign its value in the class constructor.
- BUse the final keyword and assign its value in the class constructor.
- CUse the static keyword and assign its value in a static initializer.
- DUse the final keyword and assign its value when declaring the variable.
How the community answered
(51 responses)- A4% (2)
- B86% (44)
- C10% (5)
Why each option
To ensure an Apex variable is assigned a value only once and remains constant, it must be declared with the `final` keyword, with assignment occurring either at declaration or within the class constructor.
The `static` keyword makes a variable a class-level variable, but it does not prevent its value from being reassigned after initial assignment, even if assigned in the constructor.
Declaring a variable with the `final` keyword and assigning its value within the class constructor ensures that the variable's value is set exactly once upon object instantiation and cannot be changed thereafter.
While a `static` variable can be assigned in a static initializer, the `static` keyword alone does not enforce immutability, allowing the variable's value to be changed later unless also declared `final`.
Using the `final` keyword and assigning the variable's value directly when it is declared makes it a constant, meaning its value is initialized once and cannot be modified later in the code.
Concept tested: Apex `final` Keyword for Immutability
Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_defining.htm
Topics
Community Discussion
No community discussion yet for this question.