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
:
Java1class MyClass { 2 // class body 3}
To create an object - an instance of the class - we use new
along with the class name:
Java1MyClass myObject = new MyClass();
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 ()
.
Java1class MyClass { 2 // The return type `void` indicates that this showMessage method does not return any value. 3 void showMessage() { 4 // Print the string "Hello World!" to the console. 5 System.out.println("Hello World!"); 6 } 7}
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:
Java1class MyClass { 2 // showMessage method 3 void showMessage() { 4 System.out.println("Hello World!"); 5 } 6 7 public static void main(String[] args) { 8 9 // Create an object from MyClass 10 MyClass myObject = new MyClass(); 11 12 // Call the showMessage method 13 myObject.showMessage(); // Prints: Hello World! 14 } 15}
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!