Methods
in Apex
What is a method?
A method is a block of code that
performs a specific task.
But that's too abstract, let's
look at an example
Let's imagine a rectangle
Each rectangle has a
length and a width
Width
Length
How can we represent a triangle
in the code?
Width
Length
Width
Length
public class Rectangle {
Integer width;
Integer length;
}
How can we calculate an area
of this rectangle?
Area of any rectangle is
length x width
Width Area = length x width
Length
In Code
Width Area = length x width
Length
public class Rectangle {
Integer width;
Integer length;
public Integer calculateArea() {
return width * length;
}
}
Calculating area is an action
Method is a block of code that
performs this action
Notice that we don't have
any specific values
for length & width
public class Rectangle {
Integer width;
Integer length;
public Integer calculateArea() {
return width * length;
}
}
Area calculation is a generic
action that can be performed on
any rectangle
We can use the actions to
calculate the area for any
concrete rectangle
Example in Apex
Width = 5 Area = 25
Length = 5
Width = 2 Area = 10
Length = 5
Thanks for
reading