Classes and Objects In Java
In today’s lesson, Java classes are discussed, using examples to better meet the learners’ needs.
Java Classes And Objects
As we discuss Java classes, we have noted that Java is an object-oriented language.
Classes and objects are the basis of everything in Java, as well as their attributes and methods. A bike, for instance, is an object in real life.
In addition to attributes such as the bike’s model, type, and color, there are also methods such as its ride and brakes.
The concept of a class can be thought of as an object constructor, or as a blueprint for creating objects.
Creating classes
Classes in Java can be created by using the keyword class.
Make a class named “Main” with a variable mrx as a part of it:
Main.java
public class Main{ int mrx = 35; }
It is important to remember from the Java Syntax chapter that class name should start with an uppercase letter, and class name should match the name of the java file.
Creating Objects
Objects in Java are created from classes. There are three characteristics of an object:
State: Describes an object’s data (value).
Behavior: Describes the behavior (functionality) of an object.
Identity: A unique ID identifies an object. An external user cannot see the value of the ID. The JVM uses it internally to identify each object.
We can now make objects applying the class Main, which has already been created.
When making an object of the Main class, specify the class name, then the object name, followed by the keyword new.
You need to create a new object called “my_First_Object” and print the value of the mrx variable:
Example: 
Now, Make a new object called “my_Second_Object” and print the value of the sum from the ample variable:
Example: 
Create Multiple Objects
It is possible to create multiple objects of the same class.
Two objects of the Main class can be created as shown below:
Example: 
Another example for creating more than two objects of the Main class:
Example: 
Use Multiple Classes
Objects of a class can also be created and accessed from other classes. Usually, this is done to organize classes better (one class has every attribute and method, while the other class has the main() method that executes code).
It is important that the Java file name matches the class name. As an example, the following two files have been created in the same directory:
- First_class.java
- Second_class.java
First_class.java
public class First_class { int mrx = 12; }
Second_class.java
class Second_class{ public static void main(String[] args) { First_class my_Object = new First_class(); System.out.println(my_Object.mrx); } }
After compiling both files:
C:UsersYour Name>javac First_class.java
C:UsersYour Name>javac Second_class.java
Now Run Second_class.java:
Example
In the next chapter, Java Classes Attributes will be covered in more detail.