A wrapper class in Salesforce Apex refers to a class, data structure, or abstract data type that encompasses various objects or collections of objects within its structure.
A wrapper class is essentially a custom object created by a programmer, defining its properties according to specific needs. In Salesforce, when we think of a custom object, it typically includes fields of various data types. Similarly, a wrapper class is a custom class that incorporates diverse data types or properties based on specific requirements. It allows us to encapsulate different object types or other types within a single wrapper class.
In the example below, we’ve crafted a custom list containing two distinct data types.
public class wrapper { public void callwrapper(){ List<wrapperclass> lst=new List<wrapperclass>(); contact cnn=[select id,firstname from contact limit 1]; for(Account acc_new:[select id,name from Account]){ wrapperclass obj=new wrapperclass(acc_new); lst.add(obj); } wrapperclass obj1=new wrapperclass(cnn); lst.add(obj1); system.debug(lst.size()); } public class wrapperclass{ public string name; public wrapperclass(Account x1){ name=x1.name; } public wrapperclass(contact x1){ name=x1.firstname; } } }
For any Query/doubt comment below and for quick response LinkedIn and Twitter.