Java is what we call an object-oriented language. That sounds fancy, but all it really means is that you organize your code around classes and objects. Think of a class as a blueprint and an object as the actual thing built from that blueprint.
If I want to create a hundred different cars in my program, I do not write the code
for each car individually. I write one Car class, and then I create a
hundred Car objects from it. That is the whole idea.
What is a Class?
A class is a template. It defines what properties (variables) and behaviors (methods) an object will have. Here is what a simple class looks like:
public class Car {
String brand;
int year;
void startEngine() {
System.out.println("Vroom!");
}
}
This class says every Car has a brand, a year,
and can startEngine(). That is the blueprint. But it does not actually
create any cars yet. To do that, you need objects.
Creating Objects with the new Keyword
You use the new keyword to create an object from a class. This is called
instantiation.
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.year = 2022;
myCar.startEngine();
See what happened? new Car() created an actual car object in memory.
Then I set its brand and year, and called its
startEngine() method using the dot operator.
The Dot Operator
The dot operator (.) is how you access an object's fields and methods.
You put the object name, a dot, and then whatever you want to access.
myCar.brand = "Honda";
myCar.startEngine();
The dot is basically saying "go inside this object and find this thing." It is that simple. You will use it constantly.
Multiple Classes in One Program
You can have multiple classes in the same Java file. Only one of them can be
public โ and that one must match the file name.
class Engine {
void run() {
System.out.println("Engine is running");
}
}
public class Main {
public static void main(String[] args) {
Engine e = new Engine();
e.run();
}
}
The file would be named Main.java because Main is the
public class. The Engine class is helper โ it does not need its own file.