Preface – This post is part of the Object Oriented Thinking series.
Enough theoretical talk about what classes are – it’s time to get our hands dirty and code one!
First things first, here’s where you go in your org to create a class:
Setup >> Develop >> Apex Classes >> New
For this tutorial, let’s build our X-wing class!
Every class has three components to it: [1] Attributes, [2] Methods, and [3] Constructors.
1. Attributes
Attributes are the variables that describe your class. Your class’s attributes can be any data type, collection, or even class! Think of attributes to be just like custom fields, except they exist on your class instead of a Salesforce object.
// Basic data type attributesString name; Integer protonTorpedoes; Integer deathStarsDestroyed; Decimal powerRemaining;// Attributes related to Salesforce objects - like lookups!User pilot; Account manufacturer;// Attributes related to other classes - also like lookups!LaserCannon lasers; HyperdriveEngine engine; DeflectorShield shield; AstromechDroid droid;
Note that the LaserCannon, HyperdriveEngine, and DeflectorShield classes referenced above would have to already exist for this class to save!
2. Methods
Methods are the actions available to objects of your class. You define the logic inside each method, what inputs are required (if any), and what value is returned (if any). Here’s the general template:
public ReturnType MethodName(Input1Type Input1Variable) { // Method logic goes here! }
ReturnType is simply the data type, collection, or class that’s returned when your method is called. For example, if your method took two Integers and added them together, your return type would be Integer. If you don’t want your method to return anything, use void.
MethodName is whatever you want to name your method! Make sure to choose a method name so descriptive that a Wookiee could understand it! Also, don’t forget to use camelCase.
Input1Type is the data type, collection, or class that represents your first accepted input, and Input1Variable is the variable name you’re assigning it to so you can reference it in your method’s logic. You can add more inputs to your method by separating them with commas.
Let’s create a few methods for our class:
// This method has one input and doesn't return anythingpublic void shootLasers(Integer numberOfShots) {for (Integer i = 0; i < numberOfShots; i++) { System.debug('PEW!'); } } // Notice how this method references class attributes! public void fireProtonTorpedo() {if (protonTorpedoes > 0) {System.debug('Shoop... KABOOM!!!');protonTorpedoes--; // This decrements the variable by 1 deathStarsDestroyed++; // This increments the variable by 1} } // This method returns a value!public Boolean initiateHyperdrive() {Boolean isSuccess = false; if (powerRemaining > 0.10) { System.debug('Zoom zoom, WEEE!'); powerRemaining = powerRemaining - 0.10; isSuccess = true; }return isSuccess;}
3. Constructors
Constructors are the methods that create new instances of your class, aka objects. Just like with methods, you define the logic and what inputs are required (if any). The difference with methods is that you don’t define a return type because constructors always return a new object.
The goal of a constructor is to prepare your new object for use!
// The name of the constructor "method" is always the class name public XWing(String nickname, User myUser) {name = nickname; protonTorpedoes = 2; deathStarsDestroyed = 0; powerRemaining = 1.00; pilot = myUser;}
Constructors are totally optional – Apex automatically creates a default constructor that simply creates a new object with all empty attributes.
Putting it all together…
public class XWing { // Attributes usually come first!String name; Integer protonTorpedoes; Integer deathStarsDestroyed; Decimal powerRemaining;User pilot; Account manufacturer;LaserCannon lasers; HyperdriveEngine engine; DeflectorShield shield; AstromechDroid droid;// Constructor(s) are next public XWing(String nickname, User myUser) {name = nickname; protonTorpedoes = 2; deathStarsDestroyed = 0; powerRemaining = 1.00; pilot = myUser;} // Finally comes the methodspublic void shootLasers(Integer numberOfShots) {for (Integer i = 0; i < numberOfShots; i++) { System.debug('PEW!'); } } public void fireProtonTorpedo() {if (protonTorpedoes > 0) {System.debug('KABOOM!!!');protonTorpedoes--; deathStarsDestroyed++;} }public Boolean initiateHyperdrive() {Boolean isSuccess = false; if (powerRemaining > 0.10) { System.debug('Zoom zoom, WEEE!'); powerRemaining = powerRemaining - 0.10; isSuccess = true; }return isSuccess;} }
We’re now ready to start creating objects of this class in our code!
Starting to wrap your head around the concept of objects and classes? Don’t worry if it’s still a little fuzzy to you, it takes months of practice for most people to understand these concepts.
We’ll put this class to you in the next post to “force” it in your head!
Next post: How to use objects in your code!
Hi David,
One word for you!!! You are Lord of Salesforce. It’s some what easy to grab things and work hard to become a salesforce architect in google.
But it is very tough or impossible to think about others and make other people better career helping them.
You are one of them my bro….I see lots of salesforce paid courses. This sfdc99.com is free of cost and the quality of experience you shared is no where available trust me.
Why I said ”Lord” is because you are sharing your knowledge unconditionally and in non profit way and trust me you are the person who will be the most successful man on this earth. My blessings and love.
Lots of Kudos…
Angie
Thank you Angie =) =) =) =) =)
I second that opinion
Hey devid what is the difference between Sales Cloud and Service Cloud?
what is an API?how it’s useful in salesforce?
Sales Cloud = for sales people. Basically revolves around Opportnities
Service Cloud = for support reps. Basically revolves around Cases.
API lets external systems connect into Salesforce.
Thank you david can you explain details about API’s im unable to understand…
Go Wikipedia!!
http://en.wikipedia.org/wiki/Application_programming_interface
I’ll have a tutorial on APIs this year!
David, I need basic knowledge on API for salesforce. Kindly share the link for your videos for the same.
Don’t know of any free ones off the top of my head – hope others can share this!
Hey Kuchan, check out https://www.programmableweb.com/api-university for a bit more info.
When I save this class I get an error
Error Error: Compile Error: Invalid type: LaserCannon at line 11 column 3
What is wrong with my code?
Nothing wrong with your code – we just don’t have any classes that represent LaserCannon, Hyperdrive, or DeflectorShield yet!
Try changing them to Strings temporarily =)
David
I just created blank classes for now. Thanks!
Even better =)
Input1Type is local to that class right? I think we can declare “Input1Type” inside the class.
public ReturnType MethodName() {
Input1Type Input1Variable; // can we declare this way?
// Method logic goes here!
}
Is there any difference/advantages in both the declarations?
Inputs and variables should be viewed differently, here’s an example!
public Integer addNumbers(Integer x, Integer y) {
variable sum = x + y;
return sum;
}
Then we’d call the formula using different inputs:
addNumbers(5, 4);
addNumbers(10, 20);