1

I was going through the 'Apex and Database basics' module in Trailhead and came across the following sentence in one of the units:

This example shows how the generic sObject variable can be assigned to any Salesforce object: an account and a custom object called Book__c.

sObject sobj1 = new Account(Name='Trailhead');
sObject sobj2 = new Book__c(Name='Workbook 1');

I think the sentence should have been like this: This example shows how the generic sObject variable can be assigned any Salesforce object: an account and a custom object called Book__c. What I mean is isnt the specific object being assigned to the generic object and not the other way around? I hope I've clarified my concern.

  • It's somewhat regional and opinion based, but what they are saying is not wrong. It could be written more clearly, though. – Adrian Larson Jan 4 at 14:31
1

Yes, you are correct. The specific type is indeed being assigned to the generic type. The way the trailhead module words it is indeed backwards (i.e. it describes Account acct = genericSObject;)

The action of going from a more specific type to a more general one is called up-casting. It's (almost) always possible to perform an up-cast (there are a few specific scenarios where it isn't possible, but those are the exception rather than the rule).

It is, however, also possible to down-cast in certain scenarios. As an example, try running the following code in an anonymous apex window:

Account myAccount = new Account(Name = 'my new account');
SObject genericSObj = myAccount;
Account otherAccountVariable = (Account)genericSObj;

Even though we stored the Account as a more general SObject type, Salesforce is able to remember enough about the original object in this scenario that we can down-cast back to an Account.

The (Account) part of (Account)genericSObj; is an example of explicitly type-casting an expression (whereas genericSObj = myAccount; is implicitly doing a type-cast). We need to explicitly type-cast when trying to down-cast.

0

It's just the way you are reading it, I think in English that's a correct way of saying: "You can assign an Account type to the generic sObject type". You're understanding is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.