Академический Документы
Профессиональный Документы
Культура Документы
You can convert this data type to String or from String using the toString and
valueOf methods, respectively.
Datetime ==> A value that indicates a particular day and time,such as a timestamp.
Integer ==> A 32-bit number that does not include a decimal point.
point. Longs have a minimum value of -263 and a maximum value of 263-1.
Object ==> Any data type that is supported in Apex.Apex supports primitive data
types (such as Integer), user-defined custom classes,
Time ==> A value that indicates a particular time. Time values must always be
created with a system static method
Conditional Statements
//Integerdatatype Example:
Integer age=50;
system.debug('===The age of the person is===='+age);
Id AccountId= '0016F00001w87Ql';
system.debug('===The Id of Account Object is==='+AccountId);
//Object Example
Account objAccount = new Account (Name = 'Test Chemical');
system.debug('Account value'+objAccount);
//Simple if statement
Integer age=16;
If(age>18)
{
system.debug('===The person is eligible for vote===');
}
Loops
1) do While Loop
2) While Loop
3) for Loop
// While Loop
Integer count = 1;
While(count <= 100)
{
system.debug('=====The Number is=========' + count);
count++; // Incrementing
}
// Do While Loop
Integer count = 1;
do{
system.debug('=====The Number is=========' + count);
count++; // Incrementing
}
While(count <= 100);
//For Loop
===========
Variable
Method
Class
Object
// Data Members
public Integer age;
// Constructor
public Dog(){
system.debug('====Constructor is used for Initialization of Object====');
}
// Methods
public void eat(){
system.debug('=====Dog eats=======');
}
}
Execute in developer console Anonymous window
================================================
Dog d=new Dog();
d.eat();
d.sleep();
d.bark();
================================================
public Employee(){
system.debug('===Constructor is called======');
}
Creating an Object:
Access Modifiers
Apex allows you to use the private, protected, public, and global access modifiers
when defining methods and variables.
private
This is the default, and means that the method or variable is accessible only
within the Apex class in which it is defined. If you do not specify an access
modifier, the method or variable is private.
// Data Members
private string name;
// Constructor
public Student(){
system.debug('===Constructor is Invoked====');
}
// Setter Methods
public void setName(string stdname){
name = stdname;
}
public void setAge(Integer stdAge){
age = stdAge;
}
//Getter Methods
public string getName(){
return name;
}
}
In developer console
===================================================================
Student obj = new Student();
obj.setName('Jeff Bizos');
obj.setAge(26);
obj.setCollege('Trinity College');
system.debug('====The Name of the Student is=====' + obj.getName());
system.debug('====The Age of the Student is=====' + obj.getAge());
system.debug('====The college of the Student is=====' + obj.getCollege());
===================================================================
Totest the student class
@isTest // This annotation indicates that your class is a Test Class.
public class StudentTest {
OOPS CONCEPTS:
1) Object
2) Class
3) Encapsulation
4) Inheritance
5) Polymorphism
6) Abstraction
Encapsulation:
Encapsulation in Apex is a mechanism of wrapping the data Members and code acting
on the data (Member methods) together as as single unit.
In encapsulation the variables of a class will be hidden from other classes, and
can be accessed only through the methods of their current class, therefore it is
also known as data hiding.
Provide public setter and getter methods to modify and view the variables values.
Encapsulation Example:
===================================================================================
=========================
public class Student {
// Data Members
private string name;
// Constructor
public Student(){
system.debug('===Constructor is Invoked====');
}
// Setter Methods
public void setName(string stdname){
name = stdname;
}
//Getter Methods
public string getName(){
return name;
}
}
In developer console
===================================================================
Student obj = new Student();
obj.setName('Jeff Bizos');
obj.setAge(26);
obj.setCollege('Trinity College');
system.debug('====The Name of the Student is=====' + obj.getName());
system.debug('====The Age of the Student is=====' + obj.getAge());
system.debug('====The college of the Student is=====' + obj.getCollege());
===================================================================
Totest the student class
@isTest // This annotation indicates that your class is a Test Class.
public class StudentTest {
}
===================================================================================
========================================
Inheritance:
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
The class which inherits the properties of other is known as subclass ,derived
class or child
class and the class whose properties are inherited is known as superclass ,base
class
or parent class.
Inheritance Example:
===================================================================================
=======================================
// This class can be called as Parent Class,Base Class,Super Class.
// virtual is key word for inherit this class as a parent class.
// we use virtual or abstract to inherit.
public integer c;
public Arithematic(){
system.debug('===Constructor is called=====');
}
}
=======================
Arithematic obj=new Arithematic();
obj.add(200,100);
obj.difference(400,100);
=======================
// This class can be called as Child Class,Derived Class,Sub Class.
}
=======================
ChildArithematic obj=new ChildArithematic();
obj.add(200,100);
obj.difference(400,100);
obj.product(20,30);
obj.remainder(60,5);
=======================
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Apex.
In other words, If subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.
The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access
level
Instance methods can be overridden only if they are inherited by the subclass.
Overriding Example
==================
public virtual class Bank {
public virtual Integer getRateInterest(){
return 0;
}
}
==================
public class ICICIBank extends Bank {
}
==================
public class HDFCBank extends Bank {
Method Overloading:
If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
}
=================
Arithematic1 obj=new Arithematic1();
obj.add(200,300);
obj.add(20,30,50);
=================
By changing the data type Example
=================
public class Arithematic2 {
}
================
Arithematic2 obj=new Arithematic2();
obj.add(30,50);
obj.add(30.3,50.5);
================
Static keyword:
We can apply static keyword with variables, methods, blocks and nested class.
The static keyword belongs to the class than instance of the class.
block
nested class
The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of
students etc.
The static variable gets memory only once in class area at the time of class
loading.
The Advantage of static variable is it makes your program memory efficient (i.e it
saves memory).
public class Student5 {
name = stdname;
Rollno = stdRollno;
age = stdage;
}
=================
Student5 obj1=new Student5('AbdulKalam','S001',28);
obj1.printDetails();
Student5 obj2=new Student5('Suresh','S003',28);
obj2.printDetails();
=================
Static Method:
If you apply static keyword with any method, it is known as static method.
The static method can not use non static data member or call non-static method
directly.
this and super cannot be used in static context.
public NumberIncrement(){
i++;
system.debug('===The Number is=====' + i);
}
}
========================
NumberIncrement obj1 = new NumberIncrement();
NumberIncrement obj2 = new NumberIncrement();
NumberIncrement obj3 = new NumberIncrement();
========================
// Static Method
public static void change(){
college = 'Sri Chaitanya';
system.debug('====Static Method is called=======');
}
name = stdname;
Rollno = stdRollno;
age = stdage;
// Local Variable
string sname = 'Raghu';
system.debug('===============' + sname);
}
==================
Student6.change();
Student6 obj1 = new Student6('Rajesh','std001',29);
obj1.printDetails();
Student6 obj2 = new Student6('Naresh','std002',25);
obj2.printDetails();
Student6 obj3 = new Student6('Suresh','std003',33);
jobj3.printDetails();
==================
this keyword:
`this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class instance.
this keyword is used to distinguish between local variable and instance variable.
public integer c;
public integer c;
-
public Arithematic4(){
system.debug('===3 is a Prime Number=====');
}
}
Execute in Developer Console
==========
Arithematic4 obj=new Arithematic4(200,300);
==========
public integer c;
public Arithematic5(){
// Calling the Parameterized Constructor.
this(200,100);
system.debug('===3 is a Prime Number=====');
}
}
Execute in Developer Console
============
Arithematic5 obj=new Arithematic5();
============
/*Reusing of constructor */
}
Execute in Developer Console
==========
Student2 obj=new student2('Abdulkalam',26,'IIT',45000);
obj.display();
==========
// Instance Variables
public string name;
}
Execute in Developer Console
==========
Employee3 obj=new Employee3('Jeff Bezos',28,'CEO');
obj.display();
==========
/*Here we don,t need THIS keyword because instance variable and local variable
names are
different Ex:name,empname */
// Instance Variables
public string name;
}
Execute in Developer Console
===========
Employee4 obj=new Employee4('Vivekananda',29,'CEO');
obj.display();
===========
super Keyword:
The super keyword can be used by classes that are extended from virtual or abstract
classes.
By using super, you can override constructors and methods from the parent class.
Only classes that are extending from virtual or abstract classes can use super.
You can only use super in methods that are designated with the override keyword.
// Default Constructor
public Employee1(){
mySalutation = 'Mr.';
myFirstName = 'Sachin';
myLastName = 'Tendulkar';
// Parameterized Constructor
public Employee1(string salutation,string firstname,string lastname){
mySalutation = Salutation;
myFirstName = firstname;
myLastName = lastname;
}
public SubEmployee1(){
// Calling the Parent Class Constructor
super('Mr.','Rahul','Dravid');
}
}
===============
SubEmployee1 obj=new SubEmployee1();
obj.printName();
===============
Abstraction :
It shows only important things to the user and hides the internal details.
Abstraction lets you focus on what the object does instead of how it does it.
public BankCls(){
system.debug('==Constructor is called====');
}
}
================
Points:1.Abstrsct method is a method does not have method body.
2.Every abstract method in parent class must override in child class.
3.The abstrsct method body is defined in overriding method in
child class.
/*if you extends a parent class ,that parent class must be
a virtual or abstract class then only you can extend that class*/
/*if you override a method in parent class that method must be
a virtual or abstract method then only you can extend that method */
public class ICICIBankCls extends BankCls {
}
=================
ICICIBankCls obj = new ICICIBankCls();
obj.getRateofInterest();
obj.netBanking();
obj.personalLoanLimit();
obj.MobileBanking();
=================
Interface:
=>An interface is a blueprint of a class. It has static constants and abstract
methods only.
=>There can be only abstract methods in the interface not method body. It is used
to achieve fully abstraction.
=>An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
=>A class can extend only one class, but implement many interfaces.
=>An interface can extend another interface, similarly to the way that a class can
extend another class.
=>An Apex class can only extend one parent class. Multiple inheritance is not
allowed.
Integer TotalAmount();
}
====================
public class CustomerPurchaseOrder implements PurchaseOrder
{
}
====================
public class EmployeePurchaseOrder implements PurchaseOrder
{
}
===================
void print();
}
===================
void draw();
}
===================
public class Student8 implements Printable,Drawable
{
}
===================
/*An interface can extend another interface, similarly to the way that a class can
extend another class.
An interface cannot extend multiple interfaces(one interface extends only one
interface ).*/
}
==================
public Interface Cricket extends Sports
{
}
==================
public class TtwentyCricket implements Cricket
{
}
==================
Collections:
Lists
Sets
Maps
There is no limit on the number of items a collection can hold. However, there is a
general limit on heap size.
Lists:
==================
public class ListCls {
// Iterate through the list and display each element in the list
for(string s: lst){
system.debug('===The element in the list is===' + s);
}
// Cloning a List
List<string> lstclone = lst.clone();
}
=====
ListCls.display();
================
Sets:
Set elements can be of any data type�primitive types, collections, sObjects, user-
defined types, and built-in Apex types.
=============================
public class SetCls {
// Iterate through the Set and display each element in the Set
for(string s: st){
system.debug('===The element in the Set is===' + s);
}
// Cloning a Set
Set<string> stclone = st.clone();
}
=====
SetCls.display();
=======================
Maps:
A map is a collection of key-value pairs where each unique key maps to a single
value.
Keys and values can be any data type�primitive types, collections, sObjects, user-
defined types, and built-in Apex types.
Adding a map entry with a key that matches an existing key in the map overwrites
the existing entry with that key with the new entry.
========================
public class MapCls {
emps.put(4, 'Dhoni');
// Iterate through the Map keySet and display each key in the Map
for(Integer i: emps.keySet()){
system.debug('===The key of the Map is===' + i);
}
// Iterate through the Map Values and display each Value in the Map
for(String s: emps.Values()){
system.debug('===The Value of the Map is===' + s);
}
// Cloning a Map
Map<Integer,string> empsclone = emps.clone();
}
====
MapCls.display();
==========================================
LIst,Set,Maps Lisks:
List:https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_methods_system_list.htm
Set:https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_methods_system_set.htm
Map:https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_methods_system_map.htm
==========================================
DML Statements:
The upsert DML operation creates new records and updates sObject records within a
single statement, using a specified field to determine the presence of existing
objects, or the ID field if no field is specified.
The merge statement merges up to three records of the same sObject type into one of
the records, deleting the others, and re-parenting any related records.
Upsert
Merge
Triggers:
1) before insert
2) before update
3) before delete
4) after insert
5) after update
6) after delete
7) after Undelete
Sobject records.
Undelete Triggers.
Undelete Triggers.
Sobject records.
delete Triggers.
Trigger.oldMap ==> Returns a Map of Id's to the list of
UI ================Trigger.new=================== Database
IW
DL
Apex
for(Contact c : Trigger.new){
===>2:-
for(Account a :Trigger.new){
a.SLAExpirationDate__c = Date.today() + 180;
}
===>3:-
for(Account a : Trigger.new){
a.ShippingStreet = a.BillingStreet;
a.ShippingCity = a.BillingCity;
a.ShippingState = a.BillingState;
a.ShippingCountry = a.BillingCountry;
a.ShippingPostalCode = a.BillingPostalCode;
=========
Write a trigger to automatically create three
opportunities when an Account with Annual
Revenue more than 1000000 Lakhs is created.
for(Account a : Trigger.new){
===========
Update the Rating of an Account based on the Annual Revenue.
for(Account a : Trigger.New){
===============
Programme==>2
Programme==>3
// Create a Task
Task t = new Task();
t.Description = 'Please Follow Up Test Task';
t.OwnerId = opp.OwnerId;
t.Priority = 'High';
t.Status = 'Not Started';
t.Subject = 'Follow Up Test Task';
t.WhatId = opp.Id;
Tasks.add(t);
}
for(Opportunity o : Trigger.new){
// Check if the Opportunity is Closed Won.
if(o.stagename == 'Closed Won'){
}
============
@isTest
public class ClosedOpportunityTriggerTest {
system.assertEquals('High', t.Priority);
system.assertEquals('Follow Up Test Task', t.Subject);
}
}
=========
trigger UpdateFees on Course__c (after update) {
for(Course__c c: Trigger.new){
coursemap.put(c.id, c);
}
for(Student__c s : students){
s.fees__c = coursemap.get(s.course__c).course_fees__c;
}
update students;
}
=====
@isTest
public class UpdateFeesTest {
public static @isTest void UpdateFeesTesting(){
Course__c c = new Course__c();
c.Name='Test Course';
c.Duration__c = 90;
c.Course_Fees__c = 4500;
insert c;
}
===
@isTest
public class MakeOppPrivateTest {
public static testMethod void unitTest(){
Opportunity o=new Opportunity();
o.Name = 'Test Opportunity';
o.CloseDate = Date.today() + 90;
o.StageName = 'Closed Won';
o.Description = 'Test Opportunity Description';
o.LeadSource = 'Partner Referral';
o.IsPrivate = False;
Insert o;
}
}
}
===
@isTest
public class EmailAddressChangeTest {
public static testMethod void unitTest(){
Contact c = new Contact();
c.LastName='Grills';
c.Email='beargrills@gmail.com';
insert c;
@isTest
public class TestRestrictContactByName {
}
================
@isTest
public class TestVerifyDate {
@isTest public static void CheckInDate(){
Date date1=Date.today();
Date date2=date1.addDays(29);
Date a= VerifyDate.CheckDates(date1,date2);
system.assertEquals(date2,a);
}
}
========
Two test class are same ,you can choose any type to write test class
@isTest
public class TaskUtilTest {
public static testMethod void TestTaskPriority(){
string a=TaskUtil.getTaskPriority('CA');
system.assertEquals('High', a);
string b=TaskUtil.getTaskPriority('NY');
system.assertEquals('Normal', b);
string c=TaskUtil.getTaskPriority('ABC');
system.assertEquals(Null, c);
for(Student__c s: Trigger.new){
if(s.course__c != Null){
CourseId.add(s.course__c);
system.debug('==============' + CourseId);
}
}
for(Course__c c : courses){
courseMap.put(c.Id,c);
system.debug('================' + courseMap);
}