Classes Salesforce

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

Salesforce Certified Platform Developer 1

Lesson 6: Apex Classes

©Simplilearn. All rights reserved 1


What's in It for Me

Explain Apex classes and Access Modifiers

Explain constructors

Demonstrate how to instantiate classes

Explain constants

Explain various aspects of keyword

Explain inheritance
Demonstrate how to use with and without
sharing keywords

Demonstrate how to use interfaces

Demonstrate how to use system classes and


methods

©Simplilearn. All rights reserved 2


Classes
Discuss classes

©Simplilearn. All rights reserved 3


Apex Class

An Apex Class is a template or blueprint from which objects are created. It is similar to a Java class and have
variables and methods. Variables can contain the data and methods have the logic that act upon that data.

Class

methods attributes

refuel() getFuel() Fuel


setSpeed() maxspeed
getSpeed()
drive()

©Simplilearn. All rights reserved 4


Apex Class Syntax

Let’s understand the basic syntax of an Apex class. To define an Apex class, you need to specify a couple of
keywords per the syntax given. Let’s understand each keyword and its use.

private | public | global


[virtual | abstract | with sharing | without sharing]
class ClassName [implements InterfaceNameList] [extends ClassName]
{
// The body of the class
}

©Simplilearn. All rights reserved 5


Apex Class Example

Let’s understand how Apex classes are defined using an example.

//this is a top level class

public class newCarModel {

// Additional myOuterClass code here

//inner class

class myFirstInnerClass {

// myInnerClass code here

//another inner class

class mySecondInnerClass {

// mySecondInnerClass code here

}
}

©Simplilearn. All rights reserved 6


Demo 1—Create Apex Class
Create an Apex Class using Force.com IDE and Developer Console

©Simplilearn. All rights reserved 7


Apex Class Variables and Methods
Understand the components of an Apex class

©Simplilearn. All rights reserved 8


Apex Class Variables

Apex variables are of a specific data type and contain the data on which logic is performed. Apex class contains:
variables and methods. Variables in an apex class are also called class variables as they belong to the whole
class. Individual methods in an Apex Class can also contain their own variables.
//apex class
public class newCarModel{
//class variable
public static String model = '';
//method
public void drive(){
//method variable
Integer speed = 50;
//class variable can be accessed in the method
system.debug(model);
}
}
©Simplilearn. All rights reserved 9
Apex Class Variable Syntax

The syntax of class and method


[public | private | protected | global] [final] [static] data_type variable_name
variables is quite similar, the only
[= value]
difference is method variales cannot
have any access modifiers. To declare
or initialize a class variable, you need private Integer i, j, k;
to specify the following: String helloStr = 'Hello World';

• Access modifiers public static final Integer DISCOUNT = 10;

• Definition modifier
• Data type of the variable
• Appropriate name to the variable
• Value to the variable

©Simplilearn. All rights reserved 10


Apex Class Methods

Apex Class Methods are defined in an Apex Class that provide logic to accomplish a particular task. Let’s
examine the syntax of a method.

[public | private | protected | global] [override] [static] data_type method_name


(input parameters)
{
// The body of the method
}

//public method with Integer as return type //public method with Integer as return type

public Integer maxSpeed(){ public Integer maxSpeed(){

system.debug('Max Speed'); system.debug('Max Speed');


return 100;
return 100;
}
}
Integer i = maxSpeed();
maxSpeed();

©Simplilearn. All rights reserved 11


How to Pass Values to Apex Class Methods

Sometimes two methods need to communicate


public class calculateClass {

//method that calculates sum


with each other and hence pass data so that a public static void calculateSum() {

particular logic can be implemented properly. Let’s Integer i = 5;

understand this concept with an example.


Double j = 6;

//variables i and j passed to sumMethod as paramters

Double k = sumMethod(i, j);

//this will output the sum of i and j which is 11

system.debug(k);

//another method that does the actual calculation

public static Double sumMethod(Integer a, Double b) {

//add the values

Double c = a + b;

//return variable c which is a sum of a and b

return c;

©Simplilearn. All rights reserved 12


Access Modifiers
Understand what Access Modifiers are

©Simplilearn. All rights reserved 13


Access Modifiers

Apex classes, methods, and variables can have [(none)|private|protected|public|global] declaration

different access levels depending on the access


modifier keyword used in the class or method
definition. A top-level class must have an access
//public class

public class myOuterClass {


modifier. Different types of access modifiers: //string variable accessible to code outside this class

public String str = 'Hello World';

//myOuterClass code here


Global private class myFirstClass {

// myInnerClass code here


Public }

//another private inner class

Private class mySecondInnerClass {

// mySecondInnerClass code here

Protected }

©Simplilearn. All rights reserved 14


Knowledge Check

©Simplilearn. All rights reserved 15


KNOWLEDGE
CHECK
Which of these code samples will save successfully without any error?

global class Car{ public class Car{


a. global void volvo(){
b. global void volvo(){

} }
} }

global class Car{ private class Car{


c. global void volvo{ d. private void volvo{

} }
} }

©Simplilearn. All rights reserved 16


KNOWLEDGE
CHECK
Which of these code samples will save successfully without any error?

global class Car{ public class Car{


a. global void volvo(){
b. global void volvo(){

} }
} }

global class Car{ private class Car{

global void volvo{ private void volvo{


c. d.
} }
} }

The correct answer is a.


This is correct as global method can only be contained in a global class.

©Simplilearn. All rights reserved 17


Class Constructors
Understand what Class Constructors are

©Simplilearn. All rights reserved 18


Constructors

A Constructor is a block of code that initializes class variables and set them to default values. This is important
as there might me functionality in class methods that depend on the initialization of class variables and their
default values.

public class MyClass {


// The no argument constructor
public MyClass() {
// more code here
}
}

MyClass classObject = new MyClass();

©Simplilearn. All rights reserved 19


Multiple Constructors

A class can also have multiple public class MyClass {

constructors, however, each constructor // First a no-argument constructor

public MyClass () {}
must have a different argument number
// A constructor with one argument
and type. public MyClass (Boolean call) {}

// A constructor with two arguments

public MyClass (String email, Boolean call) {}

// Though this constructor has the same arguments as the

// one above, they are in a different order, so this is legal

public MyClass (Boolean call, String email) {}


}

MyClass classObject = new MyClass();

MyClass classObject = new MyClass(true);

MyClass classObject = new MyClass('abc@email.com', true);


MyClass classObject = new MyClass(true, 'abc@email.com');

©Simplilearn. All rights reserved 20


Object Instantiation

Creating a new object from a Class is called Object Instantiation. To work with classes, non-static methods,
and attributes, we need to instantiate objects from a class using one of the constructors defined in the class.
Once you have instantiated an object, you can refer to methods and attributes using dot notation.

ClassName objectName = new ClassName();

MyClass classObject = new MyClass();

MyClass classObject = new MyClass();

MyClass classObject = new MyClass(true);

classObject.method1();

classObject.myVariable = 'Test';

©Simplilearn. All rights reserved 21


Static Methods and Variables

Static is a definition modifier. Variables and Methods both can be declared as static. Static methods and
attributes have the following characteristics:

They’re associated with a class.

They’re allowed only in outer classes.

They’re initialized only when a class is loaded.

©Simplilearn. All rights reserved 22


Constants

Constants are variables whose values do not change once they are initialized. They can be declared using
static and final keywords. The variable with these two keywords indicates that the variable can only be
assigned once, either in the declaration or with a static initializer method.

public class myCls {

//constants declared with static and final keywords

static final Integer PRIVATE_INT_CONST = 200;

static final Integer PRIVATE_INT_CONST2;

public static Integer calculate() {

return 2 + 7;

//static initialization code

static {

PRIVATE_INT_CONST2 = calculate();

©Simplilearn. All rights reserved 23


Knowledge Check

©Simplilearn. All rights reserved 24


What is the correct way of instantiating this class?
public class PersonClass {

KNOWLEDGE
public PersonClass(String firstName, String lastName, Integer phone){
CHECK /constructor code
}
}

a. static PersonClass = new myObject;

b. PersonClass myClass = new PersonClass(Jack, Sparrow, 4.5);

c. PersonClass myClass = new PersonClass(Jack, Sparrow, 4);

d. PersonClass myClass = new PersonClass('Jack', 'Sparrow', 4);

©Simplilearn. All rights reserved 25


What is the correct way of instantiating this class?
public class PersonClass {

KNOWLEDGE
public PersonClass(String firstName, String lastName, Integer phone){
CHECK /constructor code
}
}

a. static PersonClass = new myObject;

b. PersonClass myClass = new PersonClass(Jack, Sparrow, 4.5);

c. PersonClass myClass = new PersonClass(Jack, Sparrow, 4);

d. PersonClass myClass = new PersonClass('Jack', 'Sparrow', 4);

The correct answer is d.

The data type of the values being passed should match the constructors arguments data type.

©Simplilearn. All rights reserved 26


The ‘this’ Keyword
Discuss the “this” keyword

©Simplilearn. All rights reserved 27


this keyword

this keyword can be used in dot notation public class myTestThis {

to represent the current instance of the string s;

//this referring to the variable s


class it is contained in to access instance
this.s = 'TestString';
methods and variables. }
There are two ways of using this
keyword:
public class testThis {

//First constructor for the class. It requires a string parameter.

public testThis(string s2) {

//Second constructor for the class. It does not require a parameter.

//This constructor calls the first constructor using the this keyword.

public testThis() {

this('None');

©Simplilearn. All rights reserved 28


Inheritance
Discuss the “this” keyword

©Simplilearn. All rights reserved 29


Inheritance

When a class inherits the functionality of another class, instead of creating the variables and methods again,
re-use another class’s functionality that is called Inheritance. This class can also have variables and methods
of its own.

private | public | global

[virtual | abstract | with sharing | without sharing] A

class ClassName [implements InterfaceNameList] [extends ClassName]


{
// The body of the class B
}
SINGLE INHERITANCE

©Simplilearn. All rights reserved 30


Inheritance—Example

Let’s understand the concept Inheritance using the following examples:

//class declared as virtual class so that it can be overridden // This class extends Car class

public virtual class Car { public class hatchbackCar extends Car {

//virtual method can be overridden as well //method that overrides parent class’s method

public virtual void carType() { public override void carType() {

System.debug('This is a car.'); System.debug('This is a hatchback car.');

} }

public virtual Integer topSpeed() { }

return 100;
Car obj1, obj2;
}
obj1 = new Car();
}
// This outputs 'This is a car.'

obj1.carType();

obj2 = new hatchbackCar();

// This outputs 'This is a hatchback car.'

obj2.carType();

// We get the topSpeed method for free

// and can call it from the hatchbackCar instance.

Integer i = obj2.topSpeed();

©Simplilearn. All rights reserved 31


Sharing
Understand how we can make an Apex Class to follow record level security

©Simplilearn. All rights reserved 32


Sharing in Apex Classes

As seen in the code representation of how a


private | public | global
class is declared, there are two keywords: [virtual | abstract | with sharing | without sharing]
• with sharing class ClassName [implements InterfaceNameList] [extends ClassName]

• without sharing {

// The body of the class


}

//Class enforces sharing rules

public with sharing class sharingClass {

// Code here

//Class doesn't enforce sharing rules

public without sharing class noSharingClass {

// Code here
}

©Simplilearn. All rights reserved 33


Interface
Understand the concept of Interfaces

©Simplilearn. All rights reserved 34


Interface

Interfaces are similar to classes but their methods are not implemented; only method signatures are defined,
but the body of each is empty. The main advantage of Interfaces is that they provide a layer of abstraction to
your code.
// An interface that defines what a purchase order looks like in general

public interface PurchaseOrder {

// All other functionality excluded

Double discount();

// One implementation of the interface for customers // Another implementation of the interface for employees

public class CustomerPurchaseOrder implements PurchaseOrder { public class EmployeePurchaseOrder implements PurchaseOrder {

public Double discount() { public Double discount() {

return .05; // Flat 5% discount return .10; // It’s worth it being an employee! 10% discount

} }

} }

©Simplilearn. All rights reserved 35


System Classes and Methods
List some system classes and methods

©Simplilearn. All rights reserved 36


System Class and Static Methods

System is a built-in class that provides many useful methods.


Some of the important types of system class:

debug method system.debug('This is debug method');

date and time DateTime d = System.now();

Today Date d = System.today();

Assert System.assert(var1 == var2, 'var 1 and var 2 are equal');

assertEquals System.assertEquals(var1, var2);

©Simplilearn. All rights reserved 37


Limits Methods—Introduction

• Salesforce Platform is a multi-tenant environment, due to this, the Apex runtime engine enforces certain
limits.
• Apex runtime is the engine that handles Apex code on Salesforce Platform.
• These limits are enforced by Apex runtime to ensure that no one is taking up excessive Platform
resources.
• Limits Methods are there to avoid exceptions, which check the resources consumed and the amount still
available.
• Salesforce Developer must always uses these Limits methods in Apex code as that might run into
platform limits and exceptions can occur.

©Simplilearn. All rights reserved 38


Limits Methods—Versions

Limits Methods have the following two versions:

Version Example
Returns the amount of platform Limits.getHeapSize()
resource that has been used so far in
the current transaction
Contains the word “Limit” returns the Limits.getLimitHeapSize()
total amount of the resource available

©Simplilearn. All rights reserved 39


System Class and Static Methods

Following are some of the Limits methods available:

Limit Method Function

getDMLRows Returns the number of records processed by a DML statement

getDMLStatements Returns the number of DML statements processed

getHeapSize Returns amount of memory (in bytes) used for the heap

getQueries Returns the number of SOQL queries used

getQueryRows Returns the number of records returned by SOQL queries

getCPUTime Returns CPU time (in milliseconds) accumulated in current transaction

©Simplilearn. All rights reserved 40


Quiz

©Simplilearn. All rights reserved 41


QUIZ
Which of the following statements about Apex Classes is correct?
1

a. An Apex class can be declared as static

b. An Inner class be declared as static

c. A Class variable can be declared as static

d. Method variables can be declared as static

©Simplilearn. All rights reserved 42


QUIZ
Which of the following statements about Apex Classes is correct?
1

a. An Apex class can be declared as static

b. An Inner class be declared as static

c. A Class variable can be declared as static

d. Method variables can be declared as static

The correct answer is c.

Only Class variables can be declared as static.

©Simplilearn. All rights reserved 43


QUIZ
How can you call a constructor from another constructor in a class?
2

a. public class ContructorClass { public ContructorClass(string s2) { public


ContructorClass() { this('None'); }}

b. public class ContructorClass{public ContructorClass(string


s2){}publicContructorClass(){this(None);}}

c. public class ContructorClass { public ContructorClass(string s2) { } public


ContructorClass() { ContructorClass('None'); }}

d. public class ContructorClass { public ContructorClass(string s2) { } public


ContructorClass() { String str = ContructorClass('None'); }}

©Simplilearn. All rights reserved 44


QUIZ
How can you call a constructor from another constructor in a class?
2

a. public class ContructorClass { public ContructorClass(string s2) { public


ContructorClass() { this('None'); }}

b. public class ContructorClass{public ContructorClass(string


s2){}publicContructorClass(){this(None);}}

c. public class ContructorClass { public ContructorClass(string s2) { } public


ContructorClass() { ContructorClass('None'); }}

d. public class ContructorClass { public ContructorClass(string s2) { } public


ContructorClass() { String str = ContructorClass('None'); }}

The correct answer is a.

This is the right syntax. Using this keyword, we can call a contructor from another constructor.

©Simplilearn. All rights reserved 45


QUIZ
What is the correct way to call this syntax? personNameId method in this classpublic class
PersonClass { public static void personNameID(String firstName, Integer id) { }}?
3

a. PersonClass pc = new PersonClass();String personNameAndID = pc.personNameID;

b. PersonClass.personNameID();

c. PersonClass pc = new PersonClass();pc.personNameID;

d. PersonClass pc = new PersonClass();pc.personNameID();

©Simplilearn. All rights reserved 46


QUIZ
What is the correct way to call this syntax? personNameId method in this classpublic class
PersonClass { public static void personNameID(String firstName, Integer id) { }}?
3

a. PersonClass pc = new PersonClass();String personNameAndID = pc.personNameID;

b. PersonClass.personNameID();

c. PersonClass pc = new PersonClass();pc.personNameID;

d. PersonClass pc = new PersonClass();pc.personNameID();

The correct answer is b.

personNameId is a static method, hence it can only be called using className and dot notation.

©Simplilearn. All rights reserved 47


QUIZ We have these two classes with firstClass calling the Second Class. In what context will the
secondClass run?public with sharing class firstClass { secondClass sc = new secondClass();}public
4 class secondClass { //code}?

a. System Context

b. User Context

c. Depends on the code in second class

d. None of the above

©Simplilearn. All rights reserved 48


QUIZ We have these two classes with firstClass calling the Second Class. In what context will the
secondClass run?public with sharing class firstClass { secondClass sc = new secondClass();}public
4 class secondClass { //code}?

a. System Context

b. User Context

c. Depends on the code in second class

d. None of the above

The correct answer is b.

secondClass does not have any with or without sharing keyword declared on it. So the code will follow the
context of the calling class, that is, firstClass which is running in user context.

©Simplilearn. All rights reserved 49


QUIZ
Which of these statements will save and execute without error?
5

a. String str = 'Simplilearn';system.debug('str');

b. String str = 'Simplilearn';String str1 = 'learn';system.assertEquals(str, str1);

c. Date d = System.now();

d. DateTime dt = System.today(now);

©Simplilearn. All rights reserved 50


QUIZ
Which of these statements will save and execute without error?
5

a. String str = 'Simplilearn';system.debug('str');

b. String str = 'Simplilearn';String str1 = 'learn';system.assertEquals(str, str1);

c. Date d = System.now();

d. DateTime dt = System.today(now);

The correct answer is a.

Although, the debug statement will not write the str variable's value, it will not throw an error.

©Simplilearn. All rights reserved 51


Key Takeaways

©Simplilearn. All rights reserved 52


Key Takeaways

• Apex classes are where all of the logic is written in Apex.


• There are optional Definition Modifiers like virtual, abstract, and sharing.
• A constructor is a code that is invoked when an object is created from a class.
• All Apex classes have an implicit public constructor with no-arguments.
• Static methods and attributes are associated with a class, allowed only in outer classes and initialized only
when a class is loaded.
• A static variable is static only within the scope of the Apex transaction.
• Constants are variables whose values does not change once they are initialized.
• this keyword can be used in dot notation to represent the current instance of the class it is contained in to
access instance methods and variables.
• When a class inherits the functionality of another class, instead of creating the variables and methods
again, re-use another class’s functionality that is called Inheritance.
• All code in Apex, by default, runs in system context.

©Simplilearn. All rights reserved 53


This concludes “Apex Classes.”
The next lesson is “sObject Relationships.”

©Simplilearn. All rights reserved 54

You might also like