CS101: Objects

Welcome to part 3 of CS101: Objects. So far we’ve mentioned objects quite a bit. We learned in the first lesson that an object is a collection of primitive types, methods, and other objects. Then we learned that objects require a blueprint, called a class, to declare what an object contains. We’re finally ready to start instantiating some objects! Last time, we created a class called Warrior. Let’s look at that again, this time with a little more context:

Whoa, lots of new stuff! This is pretty much a complete Java program, now. Let’s break this down and see what it does. The first thing you’ve probably noticed is that we added a second class, and our existing class is inside of it. Just like classes can contain variables and methods, they can also contain other class declarations. In fact, your entire Java program is really just a set of nested classes. So where does your code begin executing? The Java VM knows about a special method called main, and that’s our entry point. A Java program’s main method always looks like this:

Don’t worry too much about the public static part, we’ll come back around to that. Just know that this method is special, because Java says so. Your program starts here. Now we’ve finally reached our object instantiation.

This is pretty similar to declaring and initializing a primitive type, right? We start with our type, Warrior, which is the same as the name of our class. That’s how we use our blueprint. We name this object  player , and we set it equal to new Warrior() . The new operator creates an instance of an object. This is a powerful aspect of objects; you can create more of them. Understanding the difference between a class and an object instance is very important. Here’s an example:

If we run this program, it outputs:

Pretty simple stuff. As you can see, changing hp or name in one object does not affect the other object. But isn’t it a pain typing out a whole line to change each variable? There has to be a better way! There is, and it’s called a constructor. A constructor is a method that runs automatically when an object is instantiated. Before we get into constructors, though, it will be helpful to review methods in general. There’s a lot to cover, so constructors and methods will be the next step in our Java journey. Until next time!

Next post: Methods


Leave a Reply

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