Hello Jetto Net followers!
Welcome to our Java Object Oriented Programming (OOP) series. In this series, we will take a step-by-step look at the OOP principles that unlock the power of Java and how to implement them in Java. Our first stop is “classes”, the basic building blocks of OOP.
Classes Object Architecture
Classes are templates we use to model real-world objects. Like the architectural floor plan of a house, a class defines the properties (characteristics) and behavior (methods) of an object. In this way, we break down complex systems into simpler parts, making them easier to understand and manage.
How to Create a Class?
Creating a class in Java is very simple. We start with the keyword class and then give our class a name. The name of a class must start with a capital letter and usually refers to the object for which it is used as a name. Inside the class are variables (properties) that represent the properties of the object and functions (methods) that represent the behavior of the object.
public class Car {
// Properties
String brand
String model
int year
String color
// Methods
public void accelerate() {
System.out.println(“The car is accelerating!”);
}
public void slow down() {
System.out.println(“The car is slowing down!”);
}
}
Display More
In the class example above, I created a class called Car. This class has four attributes named brand, model, year and color and two methods named accelerate() and slow down().
Class attributes (Properties)
Properties hold the characteristics of an object. In the car example, make, model, year and color are properties. These properties can be of different data types (String, int, double, boolean, etc.).
Class methods (Methods)
Methods define the behavior of an object. In the car example, speed up() and slow down() are methods. A method contains a sequence of commands that perform a specific task.
Access Identifiers
In Java, access modifiers are used to control access to members of a class (attributes and methods). The most commonly used access modifiers are
- public:k: Accessible from anywhere.
- private: Accessible only from within the class.
- protected: Accessible by classes in the same package and subclasses.
- default (if not specified): Accessible by classes in the same package.
Use of Classes
Classes are the foundation of object-oriented programming. Using a class, we can create an object, which is an instance of that class. Objects have the properties and methods of the class.
In the next article, we will examine in detail how objects are created and used.
See you in the next installment, happy coding!