top of page

Classes and Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor or a "blueprint" for creating objects.

Create a Class

The first thing you want to do when creating a class in Java is to make sure that none of the highlighted boxing in the closest image to the right is checked. 

​

To create a class, use the keyword class:

To create a class named "wix_Class" with a variable x:

​

matt-artz-Fu2v5drnMBA-unsplash copy.jpg
wixcl2.PNG
Capture.PNG
Capture.PNG
Capture.PNG

Creating Objects

If you look to the left you can see that I am creating a class called Player. To create an object you must have private at the front. After that, you will pick which data type you would like your object to be, and finally, you would just name your object.

Creating a Constructor

A constructor is used to initialize objects.
Constructors have to have the same name as the class, in this case, the Player will be the name of the constructor. You see in the first constructor it is pasting in the brackets all the objects, NOTE: THIS IS CALLED A REGULAR CONSTRUCTOR. Inside the curly brackets, you would put this.name = name so that name can be initialized. 
The second constructor you see in the regular brackets has nothing in it. NOTE: THIS IS CALLED A DEFAULT CONSTRUCTOR. So we hard code inside the curly brackets and later on we would change the values using are gets and sets (you will learn about these next).

Capture.PNG
Capture.PNG
Capture.PNG

Gets and Sets in Classes

Gets and sets are very simple. The sets in classes are used to change out value for another value. For example, if you look at setName you will see in the brackets is the variable that will change out the name value. Gets are used to getting the variable and see what the variable is. 

toString

A class must have something called a toString at the end of it. A toString() is an in-built method in Java that returns the value given to it in string format. Any object that this method is applied on, will then be returned as a string object. Most likely a toString is a chart/graph showing all the data. 

Capture.PNG
Capture.PNG

Multi Classes 

Click the image to learn more

bottom of page