0% found this document useful (0 votes)
8 views

Object Oriented Programming

Uploaded by

srinurk04
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Object Oriented Programming

Uploaded by

srinurk04
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

Object Oriented Programming:

============================
In Procedure Oriented Programming, each business logic should be implemented in-
terms of "Procedures and Functions". Which causes the below drawbacks.

1. In Procedure Oriented Programming, all the functions are moving around the
application.
(i.e. One function can call the other functions inside the application)

2. We can't define the level of access for the functions. (i.e. We can't
specify, up to what level the members can access)

3. It won't provide the Data Security.

To avoid this problems, we are using "Object Oriented Programming".

In Object Oriented Programming, each business logic should be implemented in-terms


of "Classes and Objects".

i.e. We are grouping a set of related methods into the smaller units called as
"Classes". To access the class members, we need a reference called as an "Object".

Class:
------
Class is a Physical Entity / Blue Print, which contains a set of members
inside it.

Class can have a set of variables, procedures, functions, properties,


Constructors, etc.

We can create "N" number of classes inside an organization. Class is used to


implement the business logic to be get referenced inside the application.

Note:
All the apex classes information will get resides inside the
"ApexClass" object.

We can query the classes information as below.

Ex:
Select id, name, body from ApexClass

Object:
-------
Once the class has been defined with the required members inside it. In-order
to access members we need a reference called as an "Object".

Object is a Logical Entity, which is used to assign / retrieve the values


from the class members.

Note:
Always memory will be allocated for the "Objects", because it holds the
values for the class members.

A class can have one or more objects. Each object contains its own memory
location.

Each object can store a different value for the class member.
Note:
Object is also called as an "Instance Of a Class".

Each object should have a unique name, through which we can reference the
class members.

Note:
Objects are purely supporting the Dynamic Memory allocation, which
provides the efficient utilization of memory.

Note:
For objects memory will be allocated inside the "Heap Memory".

Object Oriented Programming provides a set of principle as below.

1. Encapsulation:
Encapsulation is used to group / bind a set of variables and functions
together into a single unit.

Note:
Encapsulation can be achieved with the help of "Classes and
Interfaces".

2. Abstraction:
It provides the user interfaces to the users, but without providing the
complexity of the implementation.

Note:
By using Abstraction, we can achieve the "Data Hiding".

3. Inheritance:
By using this feature, we can acquire / access the features of one
class into an another. So that we can avoid the redundancy. So that we can make the
code generic.

Note:
By using Inheritance we can achieve the "Re-Usability".

4. Polymorphism:
By using this feature, we can create multiple functions inside the
class with the same name with different signature.

The functions will be differentiated in-terms of the number of


Parameters, Order of the Parameters, and the Type of the Parameters.

We have 2 Types of Polymorphism.

1. Compile Time Polymorphism / Early Binding / Static Binding.

This can be achieved with the help of "Overloading


feature".

We can overload the "Methods (MethodOverloading" and


"Constructor Overloading"

2. Runtime Polymorphism / Late Binding / Dynamic Binding:

This can be achieved with the help of "Overriding".


We can implement the "Method Overriding" in apex
programming.

Class:
======
Class is a Physical Entity, which contains the business logic, to be get referenced
inside the application.

A Class can have the combination of variables, procedures, functions, properties,


constructors, etc.

Upon defining the class, we have to follow the below syntax.

Syntax:
<Access Specifier> [With/Without Sharing] Class <ClassName>
{
// Define the Class Members..
...
...
}

Note:
1. Always class name should be starts with a "Character".
2. Class Name should be always a single word.
3. Class Name should be always "Unique". i.e. We can't define 2 classes with
the same name.
4. Compiled Apex classes information will get resides inside the "MetaData
Repository".

Access Specifier:
-----------------
Access Specifier is used to indicate the level of the access for the class and the
class members.

It can be applicable for both Class and its members. We can have a different access
specifier for each member inside the class.

Apex provides the below 4 access specifiers

1. Private:
Private access specifier can be applicable for the class members (i.e.
Variables, functions, properties, etc) and "Test Classes".

Private members of the class can be accessible from within the class
only. They can't be accessible from outside of the class.

Note:
If the user didn't specify the access specifier for a class
member. Then apex will treat the member as "Private" by default.

2. Public:
Public members can be accessible within the class, and from outside of
the class within the entire organization.

But, we can't access these members from outside of the organization.

3. Protected:
This can be applicable for the class members (like Variables,
properties, methods, etc). It can't be applicable for the classes.

Protected members of the class, can be accessible within the class and
from all the associated child classes.

4. Global:
Global members can be accessible within the organization and outside of
the organization also.

Note:
Every Batch Class (Batch Apex), Schedule Class (Schedule Apex),
Future Methods, Webservices, and API's should be defined with "Global Access
Specifier".

Note:
A Class should be defined with either "Public / Global".

Ways to Create an Apex Class:


-----------------------------
We have the below 3 ways to create an apex class.

1. By using Standard Navigation.


2. By using Developer Console
3. By using "Eclipse IDE".

/*
Define an apex class to manage the Employee Details.
*/

Public class Employees


{
public integer empId;
public string empName, address, emailId;
public Date joiningDate, birthDate;
public boolean isActive;
public decimal salaryAmount;
}

/*
Define an apex class, to manage the Project Details.
*/

public class ProjectDetails


{
public integer projectCode;
public string projectTitle, clientName, country;
public boolean projectStatus;
public decimal budgetAmount;
public Date startDate, endDate;
}

Creating the Object:


--------------------
Once the class has been defined with the required members, then we can access the
class members with the help of by creating an object.

Object:
It is nothing but an instance of a class, which is used to assign / retrieve
the values from the class members.
Syntax:
<ClassName> <objectName> = new <ClassName>();

(OR)
<ClassName> <objectName>;
<objectName> = new <ClassName>();

Ex:
Employees emp = new Employees();

ProjectDetails pDetails = new ProjectDetails();

Note:
Upon creating the object, apex will assign the "Null" value for each variable
by default.

Ex:
ProjectDetails pDetails = new ProjectDetails();

(OR)

ProjectDetails pDetails;
pDetails = new ProjectDetails();

Note:
We can create multiple objects for the same class. But object names should be
always unique.

Ex:
Employees emp = new Employees();

Employees emp1 = new Employees();

By using the Object of the class, we can assign the value to the class variables
and we can retrieve the values from the class variables.

Assigning Values to Members:


----------------------------
Once the class has been defined with some set of members, then we can assign the
values to the members as below.

Syntax:
<objectName>.<memberName> = <value>;

Ex:
Employees emp = new Employees();

emp.empId = 100001;
emp.empName = 'Suresh Kumar';
emp.salaryAmount = 45000;
emp.joiningDate = system.Today();
emp.isActive = true;

Retrieve the Values from the Members:


-------------------------------------
Once the values has been assigned to the class members, then we can retrieve the
values with the help of the object as below.
Syntax:
<objectName>.<memberName>;

Ex:
system.debug(emp.empId);
system.debug('Employee Name is...: '+ emp.empName);
system.debug('Address is....: '+ emp.address);
system.debug('Salary is...: '+ emp.salaryAmount);

/*
Create an apex Class, to manage the Student Details. And assign the values
and display the values.
*/
Class Code (Developer Console):
----------
public class StudentDetails
{
public integer studentID;
public string studentName, address;
public decimal feeAmount;
public boolean isActive;
public date birthDate, joiningDate;
}

Execution (Execute Anonymous Window):


----------
// Create the object of the class..
StudentDetails sDetails = new StudentDetails();

// Assign the values...


sDetails.StudentID = 10001;
sDetails.studentName = 'Sampath Kumar';
sDetails.isActive = true;
sDetails.feeAmount = 5000;
sDetails.Address = 'Kukatpally, Hyderabad';
sDetails.birthDate = Date.newInstance(2012, 01, 25);
sdetails.joiningDate = system.today();

// Display the values...


system.debug('Student Id is...: '+ sDetails.studentID);
system.debug('Student Name is..: '+ sDetails.studentName);
system.debug('Fee Amount is...: '+ sDetails.feeAmount);
system.debug('Birth Date is...: '+ sDetails.birthDate);
system.debug('Address is....: '+ sDetails.Address);

/*
Create an Apex class, to manage the ProjectDetails. And Assign the values and
Display the values.
*/
Class Code:
-----------
public class ProjectInfo
{
public integer projectCode;
public string title, clientName, country;
public Date startDate, endDate;
public decimal budget;
}
Execution:
----------
// Create the object of the class..
ProjectInfo pInfo = new ProjectInfo();

// Assign the values...


pInfo.projectCode = 100234;
pInfo.title = 'Product Specicalist';
pInfo.clientName = 'Tesla Motors Inc.';
pInfo.country = 'USA';
pInfo.startDate = system.today();
pInfo.endDate = system.today().AddDays(100);
pInfo.budget = 5000000;

// Display the values...


system.debug('Project Code is...: '+ pInfo.projectCode);
system.debug('Project Title is...: '+ pInfo.title);
system.debug('Client Name is...: '+ pinfo.clientName);
system.debug('Budget Amount is....: '+ pinfo.budget);
system.debug('Country name is....: '+ pinfo.country);
system.debug('Start Date is....: '+ pinfo.startDate);
system.debug('End Date is....: '+ pinfo.endDate);

ORM Technology:
===============
ORM stands for "Object Relationship & Mapping".

Salesforce purely supports the ORM features, which provides all the 3 layers of the
application upon creating an object inside the organization.

i.e. Upon creating the object, salesforce provides the below 3 layers.

1. It creates a Table.
2. It creates an User Interface (Tab)
3. It creates the Business Logic (Class)

Ex:
Object Name : Customer
Table Name : Customer__c
User Interface (Tab) : Customers
Business Logic(Class): Customer__c

i.e. Upon creating an object, salesforce provides the required business logic
in-terms of a class, which will be having the same name like as the Table Name.

Note:
Each object in salesforce(Standard / Custom) will be represented as a Class.

Ex:
Account Object will represented as an Account class..

Public Class Account


{
// Business Logic..
}

Lead Object will be represented as a Lead Class..

Public Class Lead


{
// Business Logic..
}

Position Object will be represented as a Position__c class..

Public Class Position__c


{
// Business Logic...
}

Hiring Manager Object will be represented as below..

Public class Hiring_Manager__C


{
// Business Logic...
}

Note:
Each field inside the object will be represented as a variable inside the
associated class.

Ex:
Account object fields will be represented as below..

Public Class Account


{
Public Id id, ownerid;

Public string name, industry, rating, accountnumber,


type, ownership, phone, fax, website, billingStreet,
billingCity, billingState, billingPostalCode, billingCountry, shippingCity,
active__C, pan_number__C, ... etc.

Public decimal annualrevenue;

Public DateTime createdby, lastmodifiedby;


...
...

// Salesforce provides the below 10 methods in each class by default

Public void Save()


{
// It will save the record into the associated object and will
re-direct the user to the detailed page of the record.
}

Public void Cancel()


{
// It will cancels the current operation..
}

Public void Delete()


{
// It will remove the current record from the object..
}

Public void QuickSave()


{
// It will save the record into the object.
}

// Pagination Methods..

Public void First()


{
// It will display the first set of records (Ex: 1-10)
}

Public void Next()


{
// It will display the Next Set of records.(Ex: 11-20)
}

Public void Previous()


{
// It will display the previous set of records.
}

Public void Last()


{
// It will display the last set of records..
}

Public Boolean HasPrevious()


{
// It returns TRUE, if the previous set of records exist. Else it
returns FALSE.
}

Public Boolean HasNext()


{
// It returns TRUE, if we have next set of records. Else it
returns FALSE.
}

}
Note:
By using these classes we can interact with the objects through
programatically, and we can perform all the DML operations on the object records.

Salesforce provides a separate Class for each object as below.

Object Name Class Name


-------------------------------------------
Account ---> Account
Contact ---> Contact
Opportunity ---> Opportunity
Lead ---> Lead
Case ---> Case
Task ---> Task
Event ---> Event
... ---> ...
... ---> ...
Position__c ---> Position__c
Candidate__C ---> Candidate__C
Hiring_Manager__C ---> Hiring_Manager__C
...
...

Note:
Hiring Manager Object will be represented in-terms of a class as below..

Public Class Hiring_Manager__C


{
Public id id, ownerid;

Public string name, location__C, email_id__C,


contact_number__C;

Public datetime createdby, lastmodifiedby;


}

Note:
To insert the records into the associated objects through apex programming,
we have to follow the below steps.

Step 1: Create the Object of the associated class.

Step 2: Assign the values for the required fields.

Step 3: Insert the record, by using "Insert" Statement

Step 4: Get the Confirmation, by getting the record id.

/*
Write an apex program, to insert an Account record into the object.
*/
// Step 1: Create the object of the class..
Account acc = new Account();

// Step 2: Assign the values for the required fields...


acc.Name = 'Apex Account Test';
acc.rating = 'Hot';
acc.industry = 'Finance';
acc.annualrevenue = 5000000;
acc.type = 'Prospect';
k acc.ownership = 'Public';
acc.phone = '9900998877';
acc.fax = '9900776655';
acc.website = 'www.salesforce.com';
acc.billingStreet = 'Road #2, Banjara Hills';
acc.billingCity = 'Hyderabad';
acc.billingState = 'Telangana';
acc.active__C = 'Yes';

// Step 3: Insert the record..


insert acc;

// Step 4: Get the Confirmation...


if(acc.id != null)
{
system.debug('Record Inserted Successfully. Record id is..: '+
acc.id);
}
/*
Write an apex program, to insert a Lead Record into the Lead Object.
*/

Lead ld = new Lead();

ld.firstName = 'Suresh';
ld.LastName = 'Tripathi';
ld.Company = 'Infosys';
ld.status = 'Open - Not Contacted';
ld.Rating = 'Hot';
ld.Industry = 'Banking';
ld.phone = '9900554433';
ld.fax = '9900887766';
ld.email = 'suresh@gmail.com';
ld.city = 'Hyderabad';
ld.street = 'Kukatpally';
ld.State = 'Telangana';
ld.PostalCode = '500031';
ld.Country ='India';

insert ld;

if( ld.id != null)


{
system.debug('Lead Record Inserted Successfully. Id is..: '+ ld.id);
}

/*
Write an apex program, to insert a Hiring Manager Record into the object.
*/

Hiring_Manager__c hr = new Hiring_Manager__C();

hr.Name = 'Kumar Tripathi';


hr.Location__C = 'Chennai';
hr.Email_id__c = 'kumar@gmail.com';
hr.Contact_number__C = '9900998877';

insert hr;

if(hr.id != null)
{
system.debug('Hiring Manager Record has been inserted Successfully. Id
is..: '+ hr.id);
}

Assignments:
============
1. Write an apex program, to insert a Case Record into the object.

2. Write an apex program, to insert a Contact Record into the Contact Object.

3. Write an apex program, to insert an Opportunity record into the Opportunity


object.

4. Write an apex program, to insert a Position Record into the Position object.

Creating Associated Records:


============================
By using Apex programming, we can create one or more associated records into the
objects.

We can create both Parent and Child records into the objects, which are associated
with any relationship (either Lookup / Master-Detail).

Upon creating the associated records, we need to follow the below steps.

1. Identify the relationship between the two objects, by using Schema


Builder.

2. Identify, the Parent object and the child object.

3. Identify the "Relationship Field" inside the child object.

4. Create the Parent record into the Parent object.

5. Create the Child record into the child object.

5.1. Upon creating the child record, supply the Parent record id to the
Relationship Field.

6. Insert the Child record into the object, by using "Insert" Statement.

/*
Write an apex program, to Insert an Account Record. And an associated
Contact record into the object.

Parent Object : Account


Child Object : Contact
Relationship Field : Contact: AccountID
*/

// Step 1: Create the Account Record (Parent)


Account acc = new Account();

acc.Name = 'Parent Account Record';


acc.rating = 'Hot';
acc.industry = 'Banking';
acc.type= 'Prospect';
acc.ownership = 'Private';
acc.phone = '9955443322';
acc.fax = '8877554433';
acc.website = 'www.gmail.com';
acc.active__C = 'Yes';
acc.CustomerPriority__C = 'High';

insert acc;

if(acc.id != null)
{
system.debug('Account Record Inserted Scucessfully. Account id is..: '+
acc.id);

// Step 2: Create the Child Record (Contact)


Contact con = new Contact();

con.firstName = 'Child';
con.lastname = 'Record 1';
con.title = 'Project Manager';
con.Phone = '9988000000';
con.fax = '9988776666';
con.email = 'record@gmail.com';
con.mailingCity = 'Bangalore';

// Make the Contact should be associated with the Account.


con.accountid = acc.id;

insert con;

if(con.id != null)
{
system.debug('Contact Record Created. Record Id is...: '+ con.id);
}

/*
Write an apex program, to insert a Hiring Manager Record, and an associated
Position record into the object.

Parent Object : Hiring_Manager__C


Child Object : Position__c
Relationship : Lookup
Relationship Field : Position: HiringManager__C
*/

// Step 1: Create the Parent Record...


Hiring_Manager__C hr = new Hiring_Manager__c();

hr.Name = 'Santhosh Kumar';


hr.Email_id__c = 'santhosh@gmail.com';
hr.contact_number__C = '9988776655';
hr.location__c = 'Bangalore';

insert hr;

if(hr.id != null)
{
system.debug('Hiring Manager Record Id is...: '+ hr.id);

// Step 2: Create the associated Child record..


Position__c pos = new Position__c();

pos.Name = 'SAAS Developer';


pos.Location__C = 'Bangalore';
pos.Position_status__c = 'New Position';
pos.Number_Of_Positions__C = 5;
pos.open_date__C = system.today();
pos.close_date__c = system.today().adddays(30);
pos.minimum_pay__c = 1400000;
pos.maximum_budget__c = 2000000;
pos.position_description__C = 'SAAS Developer';
pos.skills_required__c = 'SAAS Developer';
pos.Hr_Email_id__C = 'hr@gmail.com';

// Assign the position to Hiring Manager...


pos.HiringManager__C = hr.id;

insert pos;
if(pos.id != null)
{
system.debug('Position Record ID is...: '+ pos.id);
}
}

Assignments:
============
1. Write an apex program, to insert an Account Record. And an associated Case
Record.

2. Write an Apex program, to insert an Account Record, and an associated


Opportunity Record.

3. Write an apex Program, to Insert a Hiring Manager Record. And an associated


Position Record. And an Associated Candidate record to the Position.

Hiring Manager
|
--> Position
|
--> Candidate

4. Create a Lead Record into the Object. And an associated "Task Record".

Parent Object : Lead


Child Object : Task
Relationship Field : Task:WhoId
(Ex: <taskObjectName>.Whoid = <LeadRecordID>;)

5. Create a Hiring Manager Record, and an associated "Event Record"

Parent Object : Hiring_Manager__C


Child Object : Event
Relationship Field : Event:WhatID
(Ex: <eventObjectName>.Whatid = <HiringManagerID>;)

Creating Bulk Records:


======================
By using Apex programming, we can insert bulk records into the object at a time.

This can be achieved with the help of "Iterative Statements".

Syntax:
For(integer counter = 1; counter <=10; counter++)
{
// Write the code to insert the record.
}

/*
Write an apex program, to insert 100 Hiring Manager records into the object.
*/

for(integer counter = 1; counter<=100; counter++)


{
Hiring_Manager__C hr = new Hiring_Manager__c();
hr.Name = 'Bulk HR Record - '+ counter;
hr.Email_id__c = 'bulkhr'+counter+'@gmail.com';
hr.contact_number__C = '9988776655';
hr.location__c = 'Bangalore';

insert hr;

if(hr.id != null)
{
system.debug('Hiring Manager Record Id is...: '+ hr.id);
}
}

Note:
Upon performing the DML operations through the Apex Programming, we can
perform max. of 150 DML statements inside a single transaction.

When the user tries to use more than 150 DML statements inside the
transaction, then salesforce will cross the governor limits. And will abort the
transaction and the previous operations will get RolledBack.

And it will display the exception "System.LimitException: Too Many DML


Statements : 151".

This problem can be avoided with the help of "Collections".

You might also like