Wrapper Classes



Wrapper Classes: -        

A wrapper class is a container Class, a data structure which contains different objects or a collection of objects as its members.

We can wrap different object types in a wrapper class.

Collection can store only one type of data type value like : integer, String, sobject etc

Eg: List<Integer> myList = new List<Integer>();

List<String> myList = new List<String>();

But what if I want to store College with its Students ,Address records in a single object.


For the above problem :

We have the solution by creating a wrapper class with Students  and Address and reference them  in college class.

public class College {

  public   String collegeName;

  public Student stud;

    public College(String name ){

        this.collegeName = name;       

    }

    public void StudentInfo(String name, integer roll,String city, String state){

        stud =new Student();

        stud.name =name;

        stud.rollno =roll;

        stud.add.city = city;

        stud.add.state = state;       

    }

          //Student wrapper class

          public class Student{

        public String name;

        public integer rollno;

        public Address add;

        public Student(){

            add = new Address();

        }

    }

          //Address wrapper class

           public class Address {

        public String city;

        public String state;

    }

}

Post a Comment

0 Comments