Вы находитесь на странице: 1из 44

Blob ==> A collection of binary data stored as a single object.

You can convert this data type to String or from String using the toString and
valueOf methods, respectively.

Boolean ==> A value that can only be assigned true,false, or null.

Date ==> A value that indicates a particular day.

Date values must always be created with a system static method.

Datetime ==> A value that indicates a particular day and time,such as a timestamp.

Decimal ==> A 32 bit number that includes a decimal point.

Decimals have a minimum value of -232 and a maximum value of 232-1.

Double ==> A 64-bit number that includes a decimal point.

Doubles have a minimum value of -263 and a maximum value of 263-1.

ID ==> Any valid 18-character Force.com record identifier.

Integer ==> A 32-bit number that does not include a decimal point.

Integers have a minimum value of -232 and a maximum value of 232-1.

Long ==> A 64-bit number that does not includes a decimal

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,

the sObject generic type, or an sObject specific type (such as Account).

String ==> Any Set of characters surrounded by single quotes.

Time ==> A value that indicates a particular time. Time values must always be
created with a system static method

Conditional Statements

// Where Boolean,Date etc are Data types


//isMarreied is variable
//True is the assigning value for Variable(isMarried)
//system.debug(); is for printing.

//Boolean datatype Example:


Boolean isMArried = True;
system.debug('=====The personis=========' +isMArried);

//Date datatype Example:


Date DateofBirth = Date.newInstance(1992, 02, 21);
system.debug('====Suresh date of birth is======' +DateofBirth);

Date dayis = date.today();


system.debug('====day is======' +dayis);

// Decimal datatype Example:


Decimal percent=68.45 ;
system.debug('===Suresh percentage is=====' +percent);

//Double datatype Example:


Double nano=1.008278466;
system.debug('===The nano partical size is===' +nano);

//Integerdatatype Example:
Integer age=50;
system.debug('===The age of the person is===='+age);

//Long datatype Example:

Long worlpopulation= 987987673;


system.debug('===The World population is==='+worlpopulation);

Id AccountId= '0016F00001w87Ql';
system.debug('===The Id of Account Object is==='+AccountId);

//sOject specific type

Account Acc = [SELECT Name, Rating FROM Account LIMIT 1];


system.debug('===The Fields from===' +Acc);

//Object Example
Account objAccount = new Account (Name = 'Test Chemical');
system.debug('Account value'+objAccount);

//String datatype Example:


String course= 'salesforce';
system.debug('===The Course Name is==='+course);

//Time datatype Example:


Time Moviestart=Time.newInstance(4, 30, 10, 02);
system.debug('===Movie starting time is==='+Moviestart);

//DateTime datatype Example:


DateTime trainreservestion= DateTime.newInstance(2017, 02, 01, 14, 36,24);
system.debug('===The Train Reservation Date and Time is==='+trainreservestion);

//Blob example (Conversion of String to Blob and Blob to string)

String myString ='salesforce';


Blob myBlob = Blob.valueOf(myString);
system.debug('===Blob is==='+myBlob);
system.debug('===string is==='+myBlob.toString());

//Simple if statement
Integer age=16;
If(age>18)
{
system.debug('===The person is eligible for vote===');
}

//If else statement


Integer n=7;
Integer u=Math.mod(n, 2);
If(u==0)
{
system.debug('===Given number is even===');
}
else
{
system.debug('===Given number is odd===');
}

//nexted else If statement


Integer a=200;
Integer b=300;
Integer c=100;
If(a>b)
{
If(a>c)
{
system.debug('===a is greatest number===');
}
}
else If(b>c)
{
system.debug('===b is greatest number===');
}
else
{
system.debug('===c is greatest number===');
}

Loops

Apex Supports 5 different Types of Loops

1) do While Loop

2) While Loop

3) for Loop

4) for each Loop

5) SOQL 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

for(Integer i = 1; i <= 10; i++ ){


system.debug('=====The Number is=========' + i);
}

//For Loop With Break

for(Integer i = 1; i <= 10; i++ ){


if(i == 5){
break;
}
system.debug('=====The Number is=========' + i);
}

//For Loop with continue

for(Integer i = 1; i <= 10; i++ ){


if(i == 5){
continue;
}
system.debug('=====The Number is=========' + i);
}

//for each Loop


//Here we use List< > function on Account object to store total record(list of
records) in Acc variable

List<Account> Accs =[SELECT Name,Rating,Industry FROM Account];


for(account a:Accs){
system.debug('Name of the account is'+a.Name);
system.debug('Name of the account is'+a.Rating);
}

//SOQL for Loop

for(account a:[SELECT Name,Rating,Industry FROM Account]){


system.debug('Name of the account is'+a.Name);
system.debug('Name of the account is'+a.Rating);
}

===========
Variable

Method

Class

Object

string name = 'suresh';

There are two ways to go developer console

Navigation to Create an Apex Class in a UserInterface.

1.Setup ==> Build ==> Develop ==> Apex Class


2.Developer console==>File==>New==>Apex Class

// public ==> Access Modifier


// Class ==> Keyword
// Dog ==> Name of the Class
public class Dog {

// Data Members
public Integer age;

public string color;

public string breed;

// Constructor
public Dog(){
system.debug('====Constructor is used for Initialization of Object====');
}

// Methods
public void eat(){
system.debug('=====Dog eats=======');
}

public void sleep(){


system.debug('=====Dog Sleeps=======');
}

public void bark(){


system.debug('=====Dog barks=======');
}

}
Execute in developer console Anonymous window
================================================
Dog d=new Dog();
d.eat();
d.sleep();
d.bark();

================================================

public class Employee {

public string name;


public Integer age;
public string designation;
public Integer salary;

public Employee(){
system.debug('===Constructor is called======');
}

public void setName(string empname){


name = empname;
}

public void setAge(Integer empAge){


age = empAge;
}

public void setDesignation(string empDesignation){


designation = empDesignation;
}

public void setSalary(Integer empSalary){


salary = empSalary;
}

public void printDetails(){


system.debug('===The Employee name is====' + name);
system.debug('===The Employee Age is====' + age);
system.debug('===The Employee designation is====' + designation);
system.debug('===The Employee salary is====' + salary);
}

Execute in developer console Anonymous window


================================================
Employee e=new Employee();
e.setName('Abdulkalam');
e.setAge(28);
e.setDesignation('CEO');
e.setSalary(80000);
e.printDetails();
================================================
===================================================================================
===================================================================

Creating an Object:

Three Steps to creating an object from a class:

Declaration: A variable declaration with a variable name with an object type.

Instantiation: The 'new' key word is used to create the object.

Initialization: The 'new' keyword is followed by a call to a constructor.


This call initializes the new object.

Accessing Instance Variables and Methods:

Instance variables and methods are accessed via created objects.

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.

public class Student {

// Data Members
private string name;

private integer age;

private string college;

// Constructor
public Student(){
system.debug('===Constructor is Invoked====');
}

// Setter Methods
public void setName(string stdname){
name = stdname;
}
public void setAge(Integer stdAge){
age = stdAge;
}

public void setCollege(string stdCollege){


college = stdCollege;
}

//Getter Methods
public string getName(){
return name;
}

public Integer getAge(){


return age;
}

public string getCollege(){


return college;
}

}
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 {

//Defining a Test Method


// public ==> Access Modifier
// static ==> Indicates this a static method
// testMethod ==> Indicates that this a Test Method
// void ==> Return Type
// unitTest ==> Name of your Method.
public static testMethod void unitTest(){

Student obj = new Student();


obj.setName('Jeff Bizos');
obj.setAge(26);
obj.setCollege('Trinity College');
string stdname = obj.getName();
Integer stdAge = obj.getAge();
string collegename = obj.getCollege();

// Verify your Results


// system.assertEquals(expected, actual) is function to check expected
value and actual value
// if expected value and actual value is same (correct) test will pass
otherwise fail.
system.assertEquals('Jeff Bizos', stdname);
system.assertEquals(26, stdAge);
system.assertEquals('Trinity College', collegename);
}

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.

To achieve encapsulation in Apex

We have to Declare the variables of a class as private.

Provide public setter and getter methods to modify and view the variables values.

Encapsulation Example:
===================================================================================
=========================
public class Student {
// Data Members
private string name;

private integer age;

private string college;

// Constructor
public Student(){
system.debug('===Constructor is Invoked====');
}

// Setter Methods
public void setName(string stdname){
name = stdname;
}

public void setAge(Integer stdAge){


age = stdAge;
}
public void setCollege(string stdCollege){
college = stdCollege;
}

//Getter Methods
public string getName(){
return name;
}

public Integer getAge(){


return age;
}

public string getCollege(){


return college;
}

}
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 {

//Defining a Test Method


// public ==> Access Modifier
// static ==> Indicates this a static method
// testMethod ==> Indicates that this a Test Method
// void ==> Return Type
// unitTest ==> Name of your Method.
public static testMethod void unitTest(){

Student obj = new Student();


obj.setName('Jeff Bizos');
obj.setAge(26);
obj.setCollege('Trinity College');
string stdname = obj.getName();
Integer stdAge = obj.getAge();
string collegename = obj.getCollege();

// Verify your Results


// system.assertEquals(expected, actual) is function to check expected
value and actual value
// if expected value and actual value is same (correct) test will pass
otherwise fail.

system.assertEquals('Jeff Bizos', stdname);


system.assertEquals(26, stdAge);
system.assertEquals('Trinity College', collegename);
}

}
===================================================================================
========================================

Inheritance:

Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.

With the use of inheritance the information is made manageable in a hierarchical


order.

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.

extends is the keyword used to inherit the properties of a 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 virtual class Arithematic {

public integer c;

public Arithematic(){
system.debug('===Constructor is called=====');
}

public void add(integer a, integer b){


c = a+b;
system.debug('=====The sum of two numbers is===========' + c);
}

public void difference(integer a, integer b){


c = a-b;
system.debug('=====The difference of two numbers is===========' + c);
}

}
=======================
Arithematic obj=new Arithematic();
obj.add(200,100);
obj.difference(400,100);
=======================
// This class can be called as Child Class,Derived Class,Sub Class.

public class ChildArithematic extends Arithematic {

public void product(integer a,integer b){


c = a*b;
system.debug('======The Product of two numbers is========' + c);
}

public void remainder(integer a,integer b){


c = system.Math.mod(a,b);
system.debug('======The remainder is========' + c);
}

}
=======================
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 benefit of overriding is the ability to define a behaviour that's specific to


the subclass type which means a subclass can implement a parent class method based
on its requirement.

Overriding means to override the functionality of an existing method.

Rules for method overriding:

method must have same name as in the parent class

method must have same parameter as in the parent class.

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.

A method declared final cannot be overridden.

A method declared static cannot be overridden but can be re-declared.

If a method cannot be inherited, then it cannot be overridden.

Constructors cannot be overridden.

Overriding Example
==================
public virtual class Bank {
public virtual Integer getRateInterest(){
return 0;
}

}
==================
public class ICICIBank extends Bank {

public override Integer getRateInterest(){


return 8;
}

}
==================
public class HDFCBank extends Bank {

public override Integer getRateInterest(){


return 9;
}

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.

Method overloading increases the readability of the program.

There are two ways to overload the method in Apex


By changing number of arguments
By changing the data type

By changing number of arguments Example


=============================
public class Arithematic1 {

public integer result1;

public integer result2;

public void add(integer a,integer b){


result1 = a+b;
system.debug('===The Sum of Two numbers is====='+ result1);
}

public void add(integer a,integer b,integer c){


result2 = a+b+c;
system.debug('===The Sum of three numbers is====='+ result2);
}

}
=================
Arithematic1 obj=new Arithematic1();
obj.add(200,300);
obj.add(20,30,50);
=================
By changing the data type Example
=================
public class Arithematic2 {

public integer result1;

public decimal result2;

public void add(integer a,integer b){


result1 = a+b;
system.debug('===The sum of two integer numbers is=====' + result1);
}

public void add(decimal a,decimal b){


result2 = a+b;
system.debug('===The sum of two decimal numbers is=====' + result2);
}

}
================
Arithematic2 obj=new Arithematic2();
obj.add(30,50);
obj.add(30.3,50.5);
================

Static keyword:

The static keyword in Apex is used for memory management mainly.

We can apply static keyword with variables, methods, blocks and nested class.

The static keyword belongs to the class than instance of the class.

The static can be:

variable (also known as class variable)


method (also known as class method)

block
nested class

If you declare any variable as static, it is known static variable.

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 {

// Non Static or Instance Variable


public string name;

public string Rollno;

public Integer age;

// Static or Class Variable


public static string college = 'Narayana';

public Student5(string stdname,string stdRollno,Integer stdage){

name = stdname;

Rollno = stdRollno;

age = stdage;

public void printDetails(){

system.debug('==The Name of the Student is=====' + name);


system.debug('==The Rollno of the Student is=====' + Rollno);
system.debug('==The age of the Student is=====' + age);
system.debug('==The College of the Student is=====' + college);
}

}
=================
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.

A static method belongs to the class rather than object of a class.


A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.

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 class NumberIncrement {

// Non Static Variable


//public Integer i = 0;
// Static Variable
public static Integer i = 0;

public NumberIncrement(){
i++;
system.debug('===The Number is=====' + i);
}

}
========================
NumberIncrement obj1 = new NumberIncrement();
NumberIncrement obj2 = new NumberIncrement();
NumberIncrement obj3 = new NumberIncrement();
========================

/* static methiods access the static variables.


we can chanhe static variables by using static methods*/
public class Student6 {

// Non Static or Instance Variable


public string name;

public string Rollno;

public Integer age;

// Static or Class Variable


public static string college = 'Narayana';

// Static Method
public static void change(){
college = 'Sri Chaitanya';
system.debug('====Static Method is called=======');
}

public Student6(string stdname,string stdRollno,Integer stdage){

system.debug('====Constructor is getting Called====');

name = stdname;

Rollno = stdRollno;

age = stdage;

public void printDetails(){

// Local Variable
string sname = 'Raghu';

system.debug('===============' + sname);

system.debug('==The Name of the Student is=====' + name);


system.debug('==The Rollno of the Student is=====' + Rollno);
system.debug('==The age of the Student is=====' + age);
system.debug('==The College of the Student is=====' + college);

}
==================
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.

THIS keyword Examples:


/*here we use THIS key word for calling same class method ia any other methods.
if you don not take this THIS keyword here system will take THIS keyword as a
default.If you want to call any other method in current method ,
you must write that calling method first in the current method */

public class Arithematic3 {

public integer c;

public void printName(){


system.debug('==My Name is Modi=====');
}

public void printDesignation(){


// Calling the same class method
// in aniother method.
this.printName();
system.debug('===Im the Prime Minister of India=====');

Execute in Developer Console


==========
Arithematic3 obj=new Arithematic3();
obj.printDesignation();
==========
/*calling default constructor from parameter constructor*/
/* Calling the Current class Constructor means default constructor*/

public class Arithematic4 {

public integer c;
-
public Arithematic4(){
system.debug('===3 is a Prime Number=====');
}

public Arithematic4(Integer a ,Integer b){


// Calling the Current class Constructor
this();
c = a+b;
system.debug('===The Sum of two numbers is=====' + c);
}

}
Execute in Developer Console
==========
Arithematic4 obj=new Arithematic4(200,300);
==========

/*calling parameter constructor from default constructor*/

public class Arithematic5 {

public integer c;

public Arithematic5(){
// Calling the Parameterized Constructor.
this(200,100);
system.debug('===3 is a Prime Number=====');
}

public Arithematic5(Integer a ,Integer b){


c = a+b;
system.debug('===The Sum of two numbers is=====' + c);
}

}
Execute in Developer Console
============
Arithematic5 obj=new Arithematic5();
============

/*Reusing of constructor */

public class Student2 {

public string name;

public integer age;


public string college;

public integer fees;

public Student2(string stdname,integer stdage,string stdcollege){


name = stdname;
age = stdage;
college = stdcollege;
}

public Student2(string stdname,integer stdage,string stdcollege,integer


stdfees){
this(stdname,stdage,stdcollege);// Reusing the Constructor
fees = stdfees;
}

public void display(){


system.debug('== The Name of the student is====' + name);
system.debug('== The age of the student is====' + age);
system.debug('== The college of the student is====' + college);
system.debug('== The fees of the student is====' + fees);
}

}
Execute in Developer Console
==========
Student2 obj=new student2('Abdulkalam',26,'IIT',45000);
obj.display();
==========

/*Using THIS keyword To differenciate local variables and instance variables*/

public class Employee3 {

// Instance Variables
public string name;

public integer age;

public string designation;

public Employee3(string name,integer age,string designation){


this.name = name;
this.age = age;
this.designation = designation;
}

public void display(){


system.debug('===The Name of the Employee is===' + name);
system.debug('===The Age of the Employee is===' + Age);
system.debug('===The designation of the Employee is===' + designation);
}

}
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 */

public class Employee4 {

// Instance Variables
public string name;

public integer age;

public string designation;

public Employee4(string empname,integer empage,string empdesignation){


name = empname;
age = empage;
designation = empdesignation;
}

public void display(){


system.debug('===The Name of the Employee is===' + name);
system.debug('===The Age of the Employee is===' + Age);
system.debug('===The designation of the Employee is===' + designation);
}

}
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.

public virtual class Employee1 {

public string mySalutation;

public string myFirstName;

public string myLastName;

// 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 virtual void printName(){


system.debug('====The Employee Name is=====' + mySalutation + ' ' +
myLastName);
}

public string getFirstName(){


return myFirstName;
}

public class SubEmployee1 extends Employee1 {

public SubEmployee1(){
// Calling the Parent Class Constructor
super('Mr.','Rahul','Dravid');
}

public override void printName(){

// Calling the Parent Class Method


super.printName();
system.debug('===But you can call me as=====' + super.getFirstName());

}
===============
SubEmployee1 obj=new SubEmployee1();
obj.printName();
===============

Abstraction :

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

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.

Ways to achieve Abstaction:

Points:Abstract class cannot be instantiated,means you can not creat


object for abstract class(super class).
/* abstract class must have atleast one abstract method.
abstract class may have abstract,non abstract methods also.
if any method you declared as abstract,that method must be
in abstract class .
*/
// This is an Abstract Class
public abstract class BankCls {

public string city;

public BankCls(){
system.debug('==Constructor is called====');
}

// Method without a Body


// This is an Abstract Method
public abstract integer getRateofInterest();

public abstract boolean NetBanking();

// Abstract Class can Contains


// Non Abstract Methods.
public boolean MobileBanking(){
system.debug('=====MobileBanking is available====');
return true;
}

}
================
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 {

public override Integer getRateofInterest(){


system.debug('==The Rate of Interest is=== '+ 8);
return 8;
}

public override boolean netBanking(){


system.debug('===Net Banking is available in ICICI===');
return true;
}

public Integer personalLoanLimit(){


return 3000000;
}

}
=================
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.

=>It cannot be instantiated just like abstract class.

=>You cannot instantiate an interface.

=>An interface does not contain any constructors.

=>All of the methods in an interface are abstract.

=>An interface cannot contain data members.

=>An interface is not extended by a class; it is implemented by a class.

=>An interface cannot extend multiple interfaces.

=>An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.

=>Each method in an interface is also implicitly abstract, so the abstract keyword


is not needed.

=>A class can implement more than one interface at a time.

=>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.

// public ==> Access Modifier


// Interface ==> Keyword
// PurchaseOrder ==> Name of the Interface.
public Interface PurchaseOrder
{
double discount();

Integer TotalAmount();
}
====================
public class CustomerPurchaseOrder implements PurchaseOrder
{

public double discount(){


system.debug('===The discount for the Customer is 5%');
return 0.5;
}

public Integer TotalAmount(){


system.debug('===The Total Amount for the Customer is 8500');
return 8500;
}

public boolean newCustomer(){


return true;
}

}
====================
public class EmployeePurchaseOrder implements PurchaseOrder
{

public double discount(){


system.debug('===The discount for the Employee is 10%');
return 1.0;
}

public Integer TotalAmount(){


system.debug('===The Total Amount for the Employee is 6500');
return 6500;
}

}
===================

/*A class can implement more than one interface at a time.*/

public Interface Printable


{

void print();

}
===================

public Interface Drawable


{

void draw();

}
===================
public class Student8 implements Printable,Drawable
{

public void print(){


system.debug('===Hello Suresh====');
}

public void draw(){


system.debug('===Draw a Circle====');
}

}
===================

/*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 Sports


{

void setHomeTeamName(string Hname);

void setVisitingTeamName(string vname);

}
==================
public Interface Cricket extends Sports
{

void setHomeTeamScore(Integer Hscore);

void setVisitingTeamScore(Integer vscore);

}
==================
public class TtwentyCricket implements Cricket
{

public void setHomeTeamName(string Hname){

public void setVisitingTeamName(string vname){

public void setHomeTeamScore(Integer Hscore){

public void setVisitingTeamScore(Integer vscore){

}
==================
Collections:

A collection sometimes called a container is simply an object that groups multiple


elements into a single unit.
Collections are used to store, retrieve, manipulate, and communicate aggregate
data.

Apex has the following types of 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:

A list is an ordered collection of elements that are distinguished by their


indices.
List elements can be of any data type�primitive types, collections, sObjects, user-
defined types, and built-in Apex types.

Lists contains duplicate elements.

The index position of the first element in a list is always 0.

List<0,1,2,3> 0,1,2,3 are indices


Ex:List<string> lst = new List<string>{'Sachin','Rahul','Kumble'}
list indices:0=Sachin
1=Rhul
2=Kumble

==================
public class ListCls {

public static void display(){

// Declare a list and passed some values into the List.


List<string> lst = new List<string>{'Sachin','Rahul','Kumble'};

system.debug('===The elements in the list are====' + lst);

system.debug('===The Size of the list is========' + lst.size());

//Adding a new element to the List


lst.add('Virat');

system.debug('===The elements in the list after adding an element are===='


+ lst);

system.debug('===The Size of the list after adding an element is========' +


lst.size());
// Adding a duplicate element to the List
lst.add('Sachin');

system.debug('===The elements in the list after adding a duplicate element


are====' + lst);

system.debug('===The Size of the list after adding a duplicate element


is========' + lst.size());

// Display the First element from the List


system.debug('===The First Element in the List is=====' + lst.get(0));

//Removing an element from the List


lst.remove(0);

system.debug('===The elements in the list after removing an element


are====' + lst);

system.debug('===The Size of the list after removing an element is========'


+ lst.size());

// Replace an element in the List


lst.set(3,'Tendulkar');

system.debug('===The elements in the list after replacing an element


are====' + lst);

system.debug('===The Size of the list after replacing an element


is========' + lst.size());

//Sort the elements of the List in Ascending Order.


lst.sort();

system.debug('===The elements in the list after sorting the list are====' +


lst);

system.debug('===The Size of the list after sorting the list is========' +


lst.size());

// 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();

system.debug('===The elements in the Cloned list are====' + lstclone);

system.debug('===The Size of the Cloned list is========' +


lstclone.size());

//Remove all the elements from the List


lst.clear();
system.debug('===The elements in the list after removing all elements
are====' + lst);

system.debug('===The Size of the list after removing all elements


is========' + lst.size());

// Check whether a List is Empty or Not.

system.debug('===Old list is empty or not =====' + lst.isEmpty());

system.debug('===Cloned list is empty or not =====' + lstclone.isEmpty());

}
=====
ListCls.display();
================

Sets:

A set is an unordered collection of elements that do not contain any duplicates.

Set elements can be of any data type�primitive types, collections, sObjects, user-
defined types, and built-in Apex types.

A set is an unordered collection�you can�t access a set element at a specific


index. You can only iterate over set elements.

=============================
public class SetCls {

public static void display(){

// Declare a Set and passed some values into the Set.


Set<string> st = new Set<string>{'Sachin','Rahul','Kumble'};

system.debug('===The elements in the Set are====' + st);

system.debug('===The Size of the Set is========' + st.size());

//Adding a new element to the Set


st.add('Virat');

system.debug('===The elements in the Set after adding an element are====' +


st);

system.debug('===The Size of the Set after adding an element is========' +


st.size());

// Adding a duplicate element to the Set


st.add('Sachin');

system.debug('===The elements in the Set after adding a duplicate element


are====' + st);
system.debug('===The Size of the Set after adding a duplicate element
is========' + st.size());

// Check whether the Set contains an element


system.debug('===Set Contains sachin or not=====' + st.contains('Sachin'));

//Removing an element from the Set


st.remove('Sachin');

system.debug('===The elements in the Set after removing an element are===='


+ st);

system.debug('===The Size of the Set after removing an element is========'


+ st.size());

// 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();

system.debug('===The elements in the Cloned Set are====' + stclone);

system.debug('===The Size of the Cloned Set is========' + stclone.size());

//Remove all the elements from the Set


st.clear();

system.debug('===The elements in the Set after removing all elements


are====' + st);

system.debug('===The Size of the Set after removing all elements


is========' + st.size());

// Check whether a Set is Empty or Not.

system.debug('===Old Set is empty or not =====' + st.isEmpty());

system.debug('===Cloned Set is empty or not =====' + stclone.isEmpty());

}
=====
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.

A map key can hold the null value.

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.

Map keys of type String are case-sensitive.

Map<key,value> like Map<integer,string>


Ex: Map<Integer,string>{1 => 'Sachin',2 => 'Dravid',3 => 'Raina'}

========================
public class MapCls {

public static void display(){

// Declare a Map and passed some values into the Set.


Map<Integer,string> emps = new Map<Integer,string>{1 => 'Sachin',2 =>
'Dravid',3 => 'Raina'};

system.debug('===The keys of the Map are====' + emps.keySet());

system.debug('===The values of the Map are====' + emps.values());

system.debug('===The Size of the Map is========' + emps.size());

// Add a new element to the Map

emps.put(4, 'Dhoni');

system.debug('===The keys of the Map after adding a new element are====' +


emps.keySet());

system.debug('===The values of the Map after adding a new element are===='


+ emps.values());

system.debug('===The Size of the Map after adding a new element is========'


+ emps.size());

// Add a duplicate key to the Map


emps.put(1, 'Tendulkar');

system.debug('===The keys of the Map after adding a duplicate key are===='


+ emps.keySet());

system.debug('===The values of the Map after adding a duplicate key


are====' + emps.values());

system.debug('===The Size of the Map after adding a duplicate key


is========' + emps.size());

// Add a duplicate Value to the Map


emps.put(5, 'Dravid');

system.debug('===The keys of the Map after adding a duplicate value


are====' + emps.keySet());

system.debug('===The values of the Map after adding a duplicate value


are====' + emps.values());

system.debug('===The Size of the Map after adding a duplicate value


is========' + emps.size());

// Check whether the Map Contains a Particular key


system.debug('==check whether map contains key 5 or not===' +
emps.containsKey(5));

// Removing an element from the Map.


emps.remove(5);

system.debug('===The keys of the Map after removing a new element are===='


+ emps.keySet());

system.debug('===The values of the Map after removing a new element


are====' + emps.values());

system.debug('===The Size of the Map after removing a new element


is========' + emps.size());

// 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();

system.debug('===The keys of the cloned Map are====' + empsclone.keySet());

system.debug('===The values of the cloned Map are====' +


empsclone.values());

system.debug('===The Size of the cloned Map is========' +


empsclone.size());

//Remove all the elements from the Map


emps.clear();

system.debug('===The keys of the Map after removing all elements are===='


+ emps.keySet());
system.debug('===The values of the Map after removing all elements are===='
+ emps.values());

system.debug('===The Size of the Map after removing all elements


are========' + emps.size());

// Check whether a Map is Empty or Not.

system.debug('===Old Map is empty or not =====' + emps.isEmpty());

system.debug('===Cloned Map is empty or not =====' + empsclone.isEmpty());

}
====
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
==========================================

Trigger.new ==> List

(before insert,before update,after insert,after update,after undelete)

Trigger.newMap ==> Map

(before update,after insert,after update,after undelete)

Trigger.old ==> List

(before update,before delete,after update,after delete)

Trigger.oldMap ==> Map

(before update,before delete,after update,after delete)

DML Statements:

Insert ==> Creating a New Record

Update ==> Modifying an Existing Record.

Delete ==> Deleting an Existing Record.

Undelete ==> Recovering a record from the Recycle Bin.


All those statements, except a couple, are familiar database operations. The upsert
and merge statements are particular to Salesforce and can be quite handy.

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:

A Trigger is an Apex Code that fires before or after a DML Event.

The DML Events are

1) before insert

2) before update

3) before delete

4) after insert

5) after update

6) after delete

7) after Undelete

Trigger Context Variables

Trigger Context Variables are used to access the

records that fire the Trigger.

Trigger.isExecuting ==> Returns True if the Current

Context of an Apex Code is a Trigger but not a

Visualforce Page,Webservice or an Execute


Anonymous() API Call.

Trigger.isInsert ==> Returns True if the trigger is

fired due to an Insert Operation.


Trigger.isUpdate ==> Returns True if the trigger is

fired due to an Update Operation.

Trigger.isDelete ==> Returns True if the trigger is

fired due to a Delete Operation.

Trigger.isUndelete ==> Returns True if the trigger is

fired due to a Undelete Operation.

Trigger.isBefore ==> Returns True if the trigger is

fired before records are saved to the database.

Trigger.isAfter ==> Returns True if the trigger is

fired after all records are saved to the database.

Trigger.new ==> Returns a list of new versions of

Sobject records.

This Sobject List is available only in before insert,

before update,after insert,after update and after

Undelete Triggers.

Trigger.newMap ==> Returns a Map of Id's to the list of


new versions of Sobject records.

Trigger.newMap is available only in before update,

after insert,after update and after

Undelete Triggers.

Trigger.old ==> Returns a list of old versions of

Sobject records.

This Sobject List is available only in

before update,before delete,after update and after

delete Triggers.
Trigger.oldMap ==> Returns a Map of Id's to the list of

old versions of Sobject records.

Trigger.oldMap is available only in before update,before


delete,after update and after delete Triggers.

Trigger.size ==> The number of records in a Trigger

Invocation both old & new.

Difference between Before & After Triggers

BEFORE triggers should be used in below scenarios

Custom validation checks in the same object

Update the records of the same object

Setting a default value.

AFTER triggers should be used in below scenarios

If we need to use Record's ID

Inserting or Updating the related records

To send notification email post commit.

UI ================Trigger.new=================== Database
IW
DL
Apex

// trigger ==> Keyword


// TitleMandatoryTrg ==> Name of the Trigger
// on ==> Keyword
// Contact ==> Name of the Sobject
// before insert,before update ==> DML Events on which the trigger gets Invoked.
trigger TitleMandatoryTrg on Contact (before insert,before update) {

system.debug('List of records that Invoked the Trigger=======' + Trigger.new);

for(Contact c : Trigger.new){

// Check Whether Contact has a Title


if(c.Title == Null){
c.Title.addError('Title is Mandatory');
}

===>2:-

trigger SetSLAExpirationDateTrg on Account (before insert) {

system.debug('Records that caused the trigger to fire=======' + Trigger.new);

for(Account a :Trigger.new){
a.SLAExpirationDate__c = Date.today() + 180;
}

===>3:-

trigger CopyBillingAddressTrg on Account (before insert,before update) {

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.

trigger CreateMultipleOpps on Account (after insert) {

List<Opportunity> opplist = new List<Opportunity>();

for(Account a : Trigger.new){

if(a.annualrevenue > 1000000){

for(Integer i = 1; i <= 3; i++){


Opportunity o = new Opportunity();
o.name = 'oppty' + i;
o.CloseDate = Date.today()+90;
o.StageName = 'Prospecting';
o.OwnerId = a.OwnerId;
o.AccountId = a.id;
opplist.add(o);

if(opplist != Null && opplist.size() > 0){


insert opplist;
}

===========
Update the Rating of an Account based on the Annual Revenue.

Annual Revenue ==> None


Annual Revenue ==> 1 - 5Lakh ==> cold
Annual Revenue ==> 5 - 50Lakh ==> warm
Annual Revenue ==> 50lakh and above ==> Hot

trigger UpdateRating on Account (before insert,before update) {

for(Account a : Trigger.New){

if(a.annualrevenue >= 100000 && a.annualrevenue <= 500000){


a.rating = 'Cold';
}
else if(a.annualrevenue > 500000 && a.annualrevenue <= 5000000){
a.rating = 'Warm';
}
else if(a.annualrevenue > 5000000){
a.rating = 'Hot';
}
else{
a.rating = '';
}

===============
Programme==>2

trigger AutoCreateOppty on Account (after insert) {

List<Opportunity> opplist = new List<Opportunity>();

for(Account acc : Trigger.new){

Opportunity opp = new Opportunity();


opp.Name = acc.Name + ' Opportunity';
opp.StageName = 'Prospecting';
opp.CloseDate = Date.today() + 90;
opp.AccountId = acc.Id;
opp.OwnerId = acc.OwnerId;
opplist.add(opp);
}
// Check if the List has Opportunities
if(opplist.size() > 0 && !opplist.isEmpty()){
Insert opplist;
}

Programme==>3

trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {

List<Task> Tasks = new List<Task>();

for(Opportunity opp: Trigger.new){

// Check if the Stage of the Opportunity


// is Closed Won.
if(opp.StageName == 'Closed Won'){

// 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);
}

trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {

List<Task> tasklist = new List<Task>();

for(Opportunity o : Trigger.new){
// Check if the Opportunity is Closed Won.
if(o.stagename == 'Closed Won'){

//For Each Opportunity is Closed Won,Create a Task and assign to the


Opportunity Owner.
Task t = new Task();
t.Description = o.description;
t.OwnerId = o.OwnerId;
t.Priority = 'High';
t.Status = 'Not Started';
t.Subject = 'Follow Up Test Task';
t.WhatId = o.id;
tasklist.add(t);
}
}

// Check if there any tasks in the Tasklist


if(tasklist != Null && tasklist.size() > 0){
insert tasklist;
}

}
============
@isTest
public class ClosedOpportunityTriggerTest {

public static testMethod void unitTest(){


// Create an Opportunity
Opportunity o = new Opportunity();
o.Name = 'Test Opportunity';
o.CloseDate = Date.today() + 90;
o.StageName = 'Closed Won';
o.Description = 'Test Opportunity Description';
o.LeadSource = 'Web';
o.Amount = 500000;
Insert o;

// Check Whether a Task has been created.


Task t = [SELECT Id,OwnerId,Priority,Status,Subject,WhatId FROM Task WHERE
WhatId = :o.Id LIMIT 1];

system.assertEquals('High', t.Priority);
system.assertEquals('Follow Up Test Task', t.Subject);
}

}
=========
trigger UpdateFees on Course__c (after update) {

Map<Id,Course__c> coursemap = new Map<Id,Course__c>();

for(Course__c c: Trigger.new){
coursemap.put(c.id, c);
}

List<Student__c> students = [SELECT Id,Name,Fees__c,Course__c FROM Student__c


WHERE
Course__c IN :coursemap.keySet()];

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;

student__c s = new student__c();


s.Name='test Name';
s.Course__c= c.Id;
insert s;
system.debug('============='+s);

Course__c cr = [SELECT Id,Name,Duration__c,Course_Fees__c FROM Course__c


WHERE Id=:c.Id LIMIT 1];
cr.Course_Fees__c=5000;
update cr;

student__c s1 = [SELECT Id,Name,Fees__c FROM student__c WHERE Id=:s.Id


LIMIT 1];
system.debug('========'+s1);
system.assertEquals(5000,s1.Fees__c);
}
}
==========
trigger MakeOppPrivate on Opportunity (before insert,before update) {

// Iterate throgh the Records that fire this Trigger.


for(Opportunity opp: Trigger.new){

// Check if the LeadSource is Partner Referral and


// the Opportunity is not marked as Private.
if(opp.Leadsource == 'Partner Referral' && opp.isPrivate == false){
// Mark the Opportunity has Private.
opp.isPrivate = true;
}
}

}
===
@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;

Opportunity t=[SELECT Id,Name,LeadSource,IsPrivate FROM Opportunity LIMIT


1];
system.assertEquals(True,t.IsPrivate);

}
}

trigger EmailAddressChangeTrg on Contact (before update) {


// Iterate through the records that fire the Trigger.

for(Contact newcontact : Trigger.new){

// Get the existing values of the records that fire the


// Trigger using Trigger.oldMap.

Contact oldcontact = Trigger.oldMap.get(newcontact.Id);

// Check whether the email of the Contact has changed


// if there is already an email.
if(oldcontact.email != Null && newcontact.email != oldcontact.email){
// Display an error message that email address
// cannot be changed.
newcontact.email.addError('Email Address cannot be changed');
}

}
===
@isTest
public class EmailAddressChangeTest {
public static testMethod void unitTest(){
Contact c = new Contact();
c.LastName='Grills';
c.Email='beargrills@gmail.com';
insert c;

Contact cc= [SELECT Id,email From contact WHERE Id = :c.Id];


cc.email = 'beargrillssfdc@gmail.com';
try{
update cc;
}
catch(exception e){
system.debug('======Error message is=====' +e.getMessage());
}
}
}

@isTest
public class TestRestrictContactByName {

public static testMethod void unitTest(){

Contact c = new Contact();


c.firstname = 'Sachin';
c.LastName = 'INVALIDNAME';
c.Email = 'sachin@gmail.com';
try{
insert c;
}
catch(exception e){
system.debug('==error message isf====' + e.getMessage());
}
system.assert(c != Null);
Contact c1 = new Contact();
c1.firstname = 'Sachin';
c1.LastName = 'Tendulkar';
c1.Email = 'sachin@gmail.com';
insert c1;
system.assert(c1 != Null);

public class VerifyDate {

//method to handle potential checks against two dates


public static Date CheckDates(Date date1, Date date2) {
//if date2 is within the next 30 days of date1, use date2. Otherwise
use the end of the month
if(DateWithin30Days(date1,date2)) {
return date2;
} else {
return SetEndOfMonthDate(date1);
}
}

//method to check if date2 is within the next 30 days of date1


private static Boolean DateWithin30Days(Date date1, Date date2) {
//check for date2 being in the past
if( date2 < date1) { return false; }

//check that date2 is within (>=) 30 days of date1


Date date30Days = date1.addDays(30); //create a date 30 days away from
date1
if( date2 >= date30Days ) { return false; }
else { return true; }
}

//method to return the end of the month of a given date


private static Date SetEndOfMonthDate(Date date1) {
Integer totalDays = Date.daysInMonth(date1.year(), date1.month());
Date lastDay = Date.newInstance(date1.year(), date1.month(),
totalDays);
return lastDay;
}

}
================
@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);
}

@isTest public static void CheckOverDate(){


Date date1=Date.today();
Date date2=date1.addDays(32);
Date a= VerifyDate.CheckDates(date1,date2);
system.assertNotEquals(date1,a);
}

public class TaskUtil {


public static string getTaskPriority(string leadState){
if(string.isBlank(leadState) || leadState.length()>2){
return Null;
}
string taskPriority;
if(leadState=='CA'){
taskPriority='High';
}
else{
taskPriority='Normal';
}
return taskPriority;
}

}
========
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);

trigger AutoPopulateFees on Student__c (before insert) {

Set<Id> CourseId = new Set<Id>();

for(Student__c s: Trigger.new){

if(s.course__c != Null){

CourseId.add(s.course__c);

system.debug('==============' + CourseId);

}
}

//List<Student__c> students = [SELECT Id,Name,fees__c,course__c FROM Student__c


//WHERE Id IN :Trigger.newMap.keySet()];
//because still student record did not have Id
because it before insert so.
//wefollow below
List<Student__c> students = new List<Student__c>();
for(Student__c s1: Trigger.new){
Student__c s2 = s1;
students.add(s2);
}
system.debug('===========s===========' + students);

List<Course__c> courses = [SELECT Id,Name,Course_Fees__c FROM Course__c WHERE


Id IN :CourseId];

Map<Id,Course__c> courseMap = new Map<Id,Course__c>();

for(Course__c c : courses){
courseMap.put(c.Id,c);
system.debug('================' + courseMap);
}

for(Student__c std: students){


std.fees__c = courseMap.get(std.course__c).Course_Fees__c;
}

Вам также может понравиться