Constructor:-
Constructor is a special method which have the following properties.
1.Default Constructor:-
Constructor is a special method which have the following properties.
- Method name will be the same as class.
- Access specifiers will be Public.
- This method will invoked only once that is at the time of creating ab object.
- This is used to instance the data members of the class.
Ex:
Public class Testobject
{
// The no argument constructor
Public Testobject()
{
// code
}
}
There are 3 types of constructors,.
- Default Constructor
- Non-parameterized constructor
- Parameterized Constructor.
If an Apex class doesnt contain any constructor then Apex compiler b default creates a dummy constructor on the name of class when we create an object for the class.
Ex: Public class Example
{
}
Example e=new Example();
In the above example the apex class doesn't contain any constructor. so when we create object for example class Apex compiler creates a default constructor.
Ex: Public class Example()
{
}
2. Non-Parameterized Constructor & parameterized constructor:-
It is a constructor that doesn't have any parameters, or constructor that has parameters.
Ex: Public class Example
{
Integer rno;
string name;
string name;
}
Public Example(Integer x, String myname )
{
rno=x;
name=myname;
}
Public Example( )
{
//code r.no=10;
name=sam;
}
}
write a Apex programm to demonstrate usage of constructor.
Public Example(Integer x, String myname )
{
rno=x;
name=myname;
}
Public Example( )
{
//code r.no=10;
name=sam;
}
}
write a Apex programm to demonstrate usage of constructor.
- Open developer console by clicking the name on the salesforce page.
- click file & select Apx clas.
- enter the class name.
- write the Apex class.'
Ex:
Public class Employee
{
String EmployeeName;
Integer Employee no;
Public Employee( )
{
EmployeeName='Hari';
Employeno = 10;
}
Public Void show( )
{
system.debug('EmployeeName is' +EmployeeName);
system.debug('Employee is' +EmployeeNo);
}
}
5.Open the anonymous block.
Employee e1=new Employee( );
Employee e2= new Employee( );
e1.show( );
e2.show(;
This will give an output of Employee Name is Hari and Empployee no is 10.
EmployeeName is Hari
EmployeeNo 10.
No comments:
Post a Comment