How to Use Classes and Objects in Java

You can access the full course here: Java Foundations

Classes & Objects

Objects are code entities with state and behaviour. The state is represented by variables that make up various properties or attributes. The behaviour is managed by functions that the object can run; typically, these functions modify the state in some way. Classes act as blueprints for objects, specifying what variables an object should use to make up its state and also defining any functions the object might want to run. We can then create instances of these classes which are the objects themselves. We can think of this a bit like function construction where the class is the function definition as it describes what the object can do and the object is like calling the function because we are actually running some code found within the class. Classes also use special constructor functions to create instances and set up the initial state of the object.

An example of this might be a character in a game. Some attributes that a generic character has might be name, health, position, attack, defence, etc. and a character might be able to heal, move, attack, etc. We will implement some of these attributes and behaviours. We can declare our class and add attributes as variables called fields like this:

class GameCharacter {
  String name;
  int pos;
  int health;
}

Next, we need to add a move function that helps us change our position. Functions within a class are called methods. Because the method will be used to change the pos field of the GameCharacter, it doesn’t need to take in the current position or output a new position, we can add it below the fields like this:

void move(int byAmount) {
  this.pos += byAmount;
}

This function will be called on an instance of the class and will change its value of pos. The “this” keyword says that the pos variable to change is the one within the current class. Generally, if we are accessing fields or methods of the current class, we use the syntax:

this.fieldName
this.methodName

The final thing we need is a constructor. This is used to set the initial state of the object by taking in values for the variables that need to be set up and assigning the values. It acts like a regular function otherwise but is named the same as the class name and doesn’t need a return type so we would do something like this:

GameCharacter(String name, int pos, int health) {
  this.name = name;
  this.pos = pos;
  this.health = health;
}

Notice that we can use parameters with the same name as the fields. We distinguish between them again with the “this” keyword. Our final class looks like this:

class GameCharacter {

  String name;
  int pos;
  int health;

  GameCharacter(String name, int pos, int health) {
    this.name = name;
    this.pos = pos;
    this.health = health;
  }

  void move(int byAmount) {
    this.pos += byAmount;
  }
}

This should be declared before the Start class. Remember, a class is just the blueprint. To actually use this class, we have to create instances. The instances are objects: variables whose data type is the class itself. That means they use the class fields to keep track of their state and the class methods to change the state. We can create instances of GameCharacter in main like this:

GameCharacter gc = new GameCharacter(“Nimish”, 5, 100);

Note the “new” keyword. We created a variable of type GameCharacter and passed in the values of “Nimish” for name, 5 for pos, and 100 for health. In order to access the values of this object, we can do this:

String name = gc.name;
int pos = gc.pos;
int health = gc.health;

We can change them like this:

gc.pos = 10;
gc.health = 120;

And can call the function like this:

gc.move(10);

We can create as many instances of GameCharacter as we like and they can all have different values for name, pos, and health. If you’re comfortable with this class, try adding more fields and methods and then try creating your own custom class from scratch. Remember, you can always print out any values you want with:

System.out.println(variableName);

Transcript

What’s up, guys? Welcome to the final tutorial in our Java course. This is gonna be all about classes and objects. We’re gonna get an intro into what classes and objects are, how they relate to each other, and of course, how to use them. We’ll start by exploring what they are, then we’ll create a custom class, and then we’ll create an object of that class and learn how to use it. So let’s head to the code and get started.

All right, so starting from pretty much a clean slate again. Let’s talk about what classes and objects are. The weird thing is that we first have to know what an object is before we know what a class is, but we have to implement a class before we can use an object. Now we can actually see a class here but we haven’t really talked about what it is, so let’s start with the basics.

An object in code is essentially an entity with state and behavior, so it could represent anything. In a game, it could represent a character, for example, because a character has state. That’s gonna be basically the sum of all of its properties or attributes. And it has behavior.

For example, it can move, might be able to attack, might be able to pick things up, et cetera, so those would be objects. Essentially, with an object, we represent the state through variables. So these are all kind of properties and attributes that an object will have. If we’re going back to that video game character example, a character might have stuff like a name, might have a certain number of health, might have an inventory full of items, et cetera. Okay, so these are all gonna be properties or attributes that an object has that represent its state.

Now the behavioral aspects are executed through functions. For example, the player might be able to move around. In which case, it’s changing its position. It might be able to pick something up. In which case, it’s changing its inventory. It might be able to heal up by consuming something. In which case, it’s changing its health. So you can see that most of these behaviors are actually functions that will change the variables that represent its state.

Okay, so objects just represents clusters of data that have states and behavior. The state is maintained through variables, and there’s functions that represent the behavior, which for the most part just change the variable values.

Okay, so let’s launch into an example, and I figure we might as well use that game character example. So we’ll start by creating a class that represent that game character. We should probably create it before our Start class because we will be using it in here, although it doesn’t matter too much. Typically, but not always, we actually put classes in their own files, but for now, we’ll stick it all in the same file.

So we’ll create a class. We’ll call this something like a GameCharacter. Note the capitalization there. And this will need several components. So we need to start by adding its properties or its attributes. So it might have a String name. Don’t worry, we’ll assign a value later. It might have an int that is gonna represent the position, so int position. And it might have an integer that represents its health. This is gonna be a really, really basic representation.

Okay, what about some functions? So this game character might have a move function, which is going to, I’m gonna have it actually be a void. We don’t really need to output the final position, and I’ll explain why in a second. And it’s gonna be called move. We’ll take in a movement amount, which will be an integer, so int amount. And then what we’re gonna do is we’re gonna use this function to change the position for this particular character.

So what we need to do is we’re gonna say, this.pos += amount. There’s no need to output any values or anything because we’re changing the position of this game character. So when we use the keyword this, we just refer to anything that exists within this current class. So this.pos is referring to the position that belongs to a game character. And we need to do this with, well, we should be doing this with every attributes or every function that we’re calling within this class.

All right, so there’s actually one more component that we need here, and that’s gonna be a constructor, often called an initializer in other languages. So this is a special type of function that is going to be used to set up the initial states or the initial values. We also use this function to create instances of an object, which will be instances of a class which will be an object. So in our case, we can do so like this.

The constructor function has special syntax and it’s actually just the same name as the name of the class. We open up the brackets however, and then we’re gonna take in values for name, position, and health. So we’ll start with a String name, we’ll start with an int position, and an int health. Okay, then what we need to do is we need to assign the values.

So we’re going to say, this game character’s name is gonna be whatever name we pass in. We’re gonna say this game character’s position is gonna be whatever position we’re passing in. And the same with health, this.health is gonna be equal to health. Okay, cool. So a fair bit going on hit, let’s talk about what’s happening.

So again, we’re creating a GameCharacter class. This is going to be essentially the blueprint of a game character object.

So within our program here, we would create some objects that would be game character types. Each of them would have names, positions, and health, and they’d be able to move. So a class is really just a blueprint of an object, specifying which variables and which functions it should have. Each instance of GameCharacter, which will be an object, will have to have a name, position, and health. We’re gonna use this function that you constructed to set things up. In this case, just set up the initial values of name, position, and health. And then it can execute this move function to change its position.

Now again, realistically, a game character would have much more than this. They probably have maximum health, an inventory. They’d have more actions such as heal or attack or whatever. But we’re not gonna worry about that. Again, this is more just to demonstrate the concept. Now let’s create an instance of our GameCharacter so that we can actually use it because this is a little bit like a function implementation. It is showing you what should happen but it’s not actually doing anything yet.

So what we can do in our main function down here is create an instance of it. So this is actually defining a new data type every time we create a class. Instead of being, let’s say, an integer or a string, the variable is now going to be a GameCharacter type variable. We’ll just call this gc for short. And this is going to have to be an instance of a new GameCharacter. So we use the new to infer that we are actually creating an instance of GameCharacter. Note how it’s automatically using the constructor to tell us that we need a name, position, and health. So we just pass in some values here. Again, make sure they’re the correct type. Position will start at zero. Health, we’ll have maybe 100 health. And now we’ve created our first object.

So this object is an instance of the GameCharacter class. That means that our object has used this function to start up its name, position, and health, and it can move if it wants. So this gc variable has a name, a position, and a health of Nimish, 0, and 100 respectively. Okay, so now let’s talk about how to access the values or the state stored within this game character. We do so with the dot syntax. So in this case, gc dot, and you can already see a list of the possible options, health, name, and position. We can also call the move function.

So let’s say we just wanted to print out the game character’s health. What we could do is actually just do something like this. We do System.out.println and all we need to do is print the gc.health. Okay, so this is just gonna get whatever value of health is stored in this gc. In this case, 100, and it’s gonna print it out. So if we save this and we go to run it, we should just get 100 printed out. And indeed, we do.

Similarly, we can actually change it directly using basically the same functionality. So we could say something like gc.health is actually equal to 200. If we then run this again, we should see that the gc’s health is 200, and that’s because we’re assigning a new value to the variable that represents the game character’s state. So the game character’s value of health is now 200.

Similarly, if we wanted to call the move function, we could. So we could do gc.move. We can pass in an amount, maybe 10. And if we wanna print out the game character’s new position, we would do gc.pos. Okay, again, we can run this code and we’d see that our position is equal to 10 because we called the move function and that changes the position of the particular game character we’re working with.

Okay, so I know this can be a little bit of a confusing subject, but it doesn’t really need to be. Just remember that each instance has its own state, its own values for, in this case, health, position, and name, okay? And it has its own functions. We can create multiple instances of game characters, each with their own values, or we can have game characters with exactly the same values if we really want. Because this can be a slightly complex topic, I definitely recommend that you practice heavy with this one. This is really kind of bringing together everything that we’ve covered in the course so far into one, big, final topic. So really, as long as you understand the bits and pieces from before, you should be fine with this one.

So definitely practice a little bit. Try creating some new classes and new objects. And when you’re ready to move on, we can finish up by summarizing this course. Okay, so thanks for watching. See you guys in the next one.

Interested in continuing? Check out the full Java Foundations course, which is part of our One-Hour Coder Academy.