CS101: Classes

Welcome to part 2 of CS101: Classes. Last time we looked at what a variable is, and briefly introduced the idea of primitive types. The existence of primitive types implies there’s another kind of type, right? They’re called composite types, but nobody calls them that; in Java they’re just objects. An object is a collection of primitive types, other objects, and methods. Most objects have a name, which is used when you want to instantiate a new one. To instantiate an object is a fancy way to say make a new one. You see, with primitive types, Java already knows that int means “this variable is an integer”. For objects, we need a blueprint to tell Java “Hey, I need a thing made up of some numbers, a string, and these methods.” That blueprint is called a class. Let’s look at some actual code:

Here we have a simple class declaration. Our first line starts in a very similar manner to our variable declaration from last time. We have our type and name, but unlike last time, no assignment operator (that’s what we call an equals sign). Instead, we have brackets. These represent the start of a new scope. We’ll talk about scope more later, but for now just know that its a chunk of code that is separate from its surroundings. Also note the lack of a semicolon. For the most part in Java, you only use semicolons when a statement doesn’t start a new scope (marked by brackets).

Alright, so that just leaves the stuff inside our class. Our Warrior class has two integers, representing the warrior’s health points and strength, and a string for their name. A string is technically not a primitive type, but it’s a kind of object that Java allows us to use as if it were. As you can tell from the example, a string is just an object that holds some text. By putting all of this information together in a class, we keep it organized and reusable. Right now, though, this blueprint doesn’t actually do anything; a blueprint just contains instructions on how to build something. That’s where objects come in, our next topic.

Next post: Objects


Leave a Reply

Your email address will not be published / Required fields are marked *