Intro to Java: Classes & Objects

“Why Java?” is the question everyone asks me when I tell them I’m taking Treehouse’s Beginning Java class. My response is always the same, “Because Salesforce’s programming language (Apex) is very similar to Java, but Intro to Apex courses are few and far between.” For context, I do not have a background in computer science or engineering. But I love Salesforce and technology and developing solutions on the Salesforce platform. When I got stuck on Salesforce’s Get Started with Apex Trailhead module, I knew that I needed to start with the basics in order to succeed with Apex in the long run. I was familiar with an object thanks to Salesforce. At its base level, an object represents something in the world. A Pez dispenser, a go-kart, or a book. All of these things have unique attributes about them. In Java, these unique attributes are called a class. Because I love ice cream I’m going to use that as the example for my post. 🍦

image

Makes sense, right? But you’re probably asking why you need a class for ice cream. It’s totally common sense that ice cream has a flavor and a color. Sure, but what if you were working with something you weren’t familiar with? An Opportunity for example? Opportunities don’t have flavors, they have close dates and amounts. As a developer, you would have no way of knowing the potential attributes of an Opportunity without looking at its class. You’d be totally in the dark. So a class is neat template (or blueprint) for whatever object you want to create. Here’s my ice cream class in code: class IceCream{

String flavor;

String texture;

String color;

String brand;

} I’m declaring the class at the beginning and giving it a name (IceCream). Then inside the curly braces I’m declaring the attributes (or variables) that my IceCream class has. “String” means that I’m expecting a word as my value, i.e. mint-chocolate chip. But what about objects? Objects are created from classes. This is called instantiation. You can create many objects from one class. Note: If you are coming to Java from Salesforce, this concept is a bit confusing. Because in our world there are objects (like the Opportunity object) and then records created inside the object. Java doesn’t use the concept of records. They use classes (which is Salesforce’s version of an object) and then objects (which I knew as records). Not so bad, right? In my next post, I’ll talk about modifiers (which give you a certain type of access to the variables). Thanks to Craig Dennis & Doug Ayers for helping me with the concepts in this post.