As mentioned in a previous post, object-oriented programming is a paradigm in which we model our problem’s actors (objects) using some structures called classes. A class defines the common structure of all objects (of the same type) will share.

An object could be described as a sort of entity that has some attributes (state of the object) and can execute some tasks (behavior of the object). Objects are created based on the class structure.
To start using the OOP paradigm, let’s make use of one of the most widely used oop programming languages: Java.
In Java, to write a class we must create a file with the .java extension and named after the class’ name.
The structure will start with the class keyword and the name of our new class, its content must be wrapped by curly braces.

Inside the curly braces, we can start now adding the attributes making use of variables. In Java, we must define the variable’s type before its name.

To define behaviours we use methods, in Java, every method must define its return type, if none it should be set to void, a name and a set of arguments in parentheses (if any is needed).

The complete structure will look like the following:
class Car{
String color;
int size;
String engine;
double price;
String model;
void drive(){
System.out.println("driving the " + color + " car");
}
void park(){
System.out.println("parking the " + color + " car");
}
void start(){
System.out.println("starting the " + color + " car");
}
void stop(){
System.out.println("stopping the " + color + " car");
}
}
Once we have the class structure, we can start using this class for creating objects, to do so, we must make use of the new operator, it will create an object from the given class. The method used next to the new operator is called the constructor, and every class has one with no arguments by default, in some cases we can define our own constructor (s).

Finally, we can access its attributes/methods using the dot operator (.):

To test it, let’s create an object from the Car class, assign some values to its properties, and execute some behaviors from the main method of a Java Application.
public class JavaApp {
public static void main(String[] args) {
Car myCar = new Car();
//Setting the car's attributes
myCar.color = "red";
myCar.size = 123;
myCar.engine = "V3";
myCar.price = 40000;
myCar.model = "LT";
//Executing behaviors of the car
myCar.start();
myCar.drive();
}
}
The result will get when executing this code will look like the following:
starting the red car
driving the red car
Classes Java Object Oriented Programming Objects programming 101