Hello! Today, we will be diving into Java classes, a fundamental topic in Object-Oriented Programming. Classes describe how objects should look and behave. By the end of this lesson, you will understand what classes are and you will be able to create and use classes in Java. Let's get started!
In Java, a class is a cornerstone tool. It is a blueprint from which we create objects. For example, a Bicycle
class could include attributes such as gear
and speed
, as well as methods such as applyBrake
and changeGear
. Just as a caterer uses a recipe to make cookies, we use classes to create objects in programming.
The creation of a class begins with the class
keyword, followed by a unique class name. It's standard in Java for class names to begin with a capital letter. Here's how to define an empty class called MyClass
:
To create an object - an instance of the class - we use new
along with the class name:
Objects perform actions (or stop them) through methods. A method is a set of instructions that performs an action when executed. In our class, we define a method to display a message. This syntax requires a return type, a name, and parentheses ()
.
Now, we create an object and call our method. To invoke a method, we use dot notation .
on the object, followed by the method name and parentheses:
The program prints "Hello World!"
to the console. We've now executed a method with an object successfully!
Congrats! We began with the basics, then looked at how to create classes. We learned about methods and how they encapsulate actions inside classes. We also wrote a basic Java program.
You are now ready for more complex concepts like attributes, encapsulation, and inheritance in upcoming lessons. Stay tuned for hands-on exercises!
