Basic Components



Classes are the basic components in object-oriented programming, essentially a program created using a programming language that follows this paradigm it is composed of various classes, which could also be defined as its cells. A Class in reality it is not something 'concrete', but rather the concept of something that exists within the program, a sort of mold that is used to create an object that represents in concrete that Class. Only after the class has materialized (it has been instantiated) will it be possible to use its functionalities, therefore its methods and its variables (except for the methods and variables with the static modifier, which we will see subsequently).
Let's see a simple example of a Java class that contains the basic components:

public class SumClass {

    // Instance variables
    private int a;
    private int b;

    // Constructor method without parameters
    public SumClass() {

    }
    // Constructor method with parameters
    public SumClass(int a, int b) {
        this.a = a;
        this.b = b;
    }

    // Setter and Getter Methods of a
    public void setA(int a) {
        this.a = a
    }
    public int getA() {
        return a;
    }

    // Sum Method
    public int sumNumbers() {
        return a + b;
    }
}

Each element defined within the class has a specific purpose, which we will examine gradually.

We note that in the first lines of code of our class two variables are declared, a and b. They are of type int (integer) and are private, or usable only within that class (we will see Access Modifiers later). The variables of type int by default are initialized to 0. Let's see an example:

    SumClass sumClass = new SumClass();
    System.out.println(sumClass.getA());

Output: 0

NOTE: If we had not defined the constructor without parameters, we have had an error in compiling!

In the first line of code we have concretized the class, in computer science terms it is said that we instanced it. sumClass refers to the reference to the memory address it points to that object of type SumClass, not the object itself.

If we wanted to initialize the variables, we would have two options for the variable a and just an option for variable b, because we have not defined neither a setter method nor a getter method for this variable. Now let's see how to use the constructor method for initialize both variables:

    SumClass sumClass = new SumClass(5, 10);
    System.out.println(sumClass.getA());
    System.out.println(sumClass.sumNumbers());

Output: 5 15

So in this way the variable a has been initialized to 5, the variable b to 10 and their sum is worth 15.