Use of getter and setter methods for each field in Wrapper classes

I understand that wrapper class is like a custom object that you can define in an Apex class but I am not sure why getter and setter methods are used for each field in a wrapper class. What is the purpose of it?

public with sharing class GetAllOpportunities { @AuraEnabled(cacheable=true) public static List getAllOpps() { List listOpp = [SELECT Id, Name ,StageName, CloseDate FROM Opportunity Order By Name asc]; List response = new List(); for(Opportunity opp : listOpp){ DataTableWrapper obj = new DataTableWrapper(); obj.oppId = opp.Id; obj.name = opp.Name; obj.nameUrl = '/'+opp.Id; obj.stageName = opp.StageName; obj.closeDate = opp.CloseDate; response.add(obj); } return response; } private class DataTableWrapper { @AuraEnabled public Id oppId {get;set;} @AuraEnabled public String name {get;set;} @AuraEnabled public String nameUrl {get;set;} @AuraEnabled public String stageName {get;set;} @AuraEnabled public Date closeDate {get;set;} } }


Answered by Kayla Shinn

Wrapper Class Salesforce: A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or collections of objects as its members.

A wrapper class is a custom object defined by a programmer wherein he defines the wrapper class properties. Consider a custom object in salesforce, what do you have in it? fields right? different fields of different data types. Similarly wrapper class is a custom class which has different data types or properties as per requirement. We can wrap different objects types or any other types in a wrapper class.

Below is the code for your reference

APEX-

    public inherited sharing class LWCExampleController { @AuraEnabled(Cacheable = true) public static List fetchAccAndCons() { List lstWrapper = new List(); for(Account acIterator : [ SELECT Id, Name, (Select Id, Name From Contacts) FROM Account WHERE Id = '001B000000vZWOHIA4'] ) { lstWrapper.add(new WrapperDemo(acIterator, acIterator.Contacts)); } return lstWrapper; } // Wrapper Class public class WrapperDemo { @AuraEnabled public Account objAcc; @AuraEnabled public list lstCons; public WrapperDemo(Account acc, list lstCons) { this.objAcc = acc; this.lstCons = lstCons; } } }


Your Answer

Interviews

Parent Categories