JAVA LESSON 13 – CLASSES AND OBJECTS

 


INTRODUCTION

In today's free Java lesson, we will explain what a class is and how it is used to create objects. As you can understand, our journey into the world of object-oriented programming is just beginning.

In the previous sections, we talked quite a bit about the basic principles and commands of Java. Although we covered almost all the elements that make up a simple Java program, there are still a few remaining—such as the concept of a method—which we will have the opportunity to explore once we understand what a class is and what an object means in programming.

CLASS STRUCTURE

Java was designed from the ground up to function as an object-oriented programming language. Simply put, this means that any code we write must be contained either within a class or within an interface. But let’s start from the beginning and look at what a class really is.

Let’s consider the scenario where we’ve been assigned to write a Java program that allows us to store information about a company’s employees. The first step we need to take is to think for a moment about what the main object of interest is in this problem. The answer is simple – the employee.

Basically, any noun—like employee, car, invoice, etc.—represents the concepts we're truly interested in. So now, as the second step, we need to think about how to represent a real-world object (like an employee) in code. The answer to this question is also simple – this is done by creating a class.

So, what is a class? A class—and this can be considered your general rule—is the way we describe real-world objects in code. Following the same logic, if we were assigned to create a program for a factory that produces cars, then one of the objects we would need to represent in code with a class would be the car. With this definition, as simple as it may sound, you won’t go wrong when creating your first Java programs.

Alright, so in order to represent the employee in our scenario through code, we need to create a class. And how do we create a class? You’ve already done this in every program you’ve written so far. The general structure of a class is as follows:

class classname {

}

Defining a class requires us to first write the keyword class, followed immediately by the name we want to give the class. The code that belongs to the class is enclosed within curly braces { }.

So, to start, we need to create a class named Employee.

Employee.java

package com.example;


public class Employee {

}

The name of the file containing the class must be the same as the class name. So, in our example, we create a file named Employee.java that contains the Employee class.

So, we have created a class and named it Employee, but we haven’t yet described the concept of an employee in code.

Each class can describe its objects using two programming approaches: variables and methods. Variables describe the characteristics of the object (like age, salary, etc.), while methods describe the actions the object can perform (like calculateOvertime, vacationTimeLeft, etc.). In our example, to start with, we will only add variables. Later, when we learn about methods, we will add those to our program’s logic as well.

What exact information do we need to know about each employee? Let’s assume it’s enough to know their name, tax ID number (AFM in Greece), employee number, salary, and the department they work in. Of course, we could add more variables, but these are sufficient for our example. The logic, after all, remains the same.

As we’ve already mentioned, we need to define these characteristics as variables inside the class we created. Declaring variables is the same as you already know, with the additional detail of access specifiers (also called access modifiers). To properly declare a variable, we need to specify three things:

A   Access specifier – This indicates which other classes or parts of Java can access these variables. Access is specified by placing one of the following keywords before the variable: public, private, protected, or nothing (which is considered default). For now, we will leave the access as public, without restricting access to the variables.

d    Data type – Just like with any variable declaration, for the variables that belong to a class, we need to specify from the start the kind of values they will hold.

·      Name – This is the name we give to the variable.

The concept of variables at the class level might not be completely clear to you yet, but hang tight—we’ll finish our code soon, and you’ll see how they work. So, let’s go ahead and add our variables to the class.

Employee.java

package com.example;


public class Employee {

public String name;

public int AFM;

public int employeeId;

public double salary;

public String department;

}

When variables are defined at the class level, like in the example above, and not inside a method like main(), they are called instance variables because each object (instance) created from the class will have its own copy of all those variables. Managing them is the responsibility of each individual object.

By default, all variables start with zero or "empty" values according to Java’s rules.



So, what is a class? It’s the programming representation of an object. And what is a class used for? It’s the blueprint we use to create objects of the type Employee. That’s why people often describe classes as blueprints—because we can create objects from them. 

The Employee class is ready. However, as you already know, no Java program runs without the main() method. So, we’ve created the blueprint that will create Employee objects, but we still don’t have the ability to execute anything. How do we do that?

The best way is to create another class that contains the main() method, from which we will call all the other classes we have created and create objects from them. Let’s create, within the same package, another class named EmployeeDemo with the following code:

EmployeeDemo.java

package com.example;


public class EmployeeDemo {

public static void main(String[] args) {

}

}

The code in main() doesn’t yet create or handle any objects. What else do we need to write to create our first object? Let’s write the code first, and then we’ll explain it.

Employee michail = new Employee();

This is where all the theory and the concept of object-oriented programming come together. But let’s take a closer look at exactly what’s happening.

Every time we create a simple class, Java provides us with a mechanism called a constructor to create objects from that class. A constructor looks like a method because it has a name followed by parentheses, but with one big difference — the constructor’s name is always exactly the same as the class name. This way, Java knows from which class to create the object we need.

To complete the process, we need to add the keyword new before the constructor. What we’ve done so far is create a new object in our computer’s memory. The command that accomplishes this is the code on the right side of the equals sign.

new Employee();

Here we start to see how Java differs from other programming languages like C and C++. When an object is created, Java doesn’t allow us direct access to the object because it wants to take responsibility for managing memory—especially creating and deleting objects from memory to avoid potential memory leaks.

This is a big advantage for us because if we were programming in another language, we’d have to track the object from the moment it’s created until it’s deleted. That would require a lot of code and effort on our part. Fortunately, Java frees us from this task with its own internal mechanism called the garbage collector, which is active as soon as we install the Java JDK on our computer.

But if Java doesn’t let us access the object we just created directly, how can we assign values to the employee’s attributes? The answer is simple — by creating a reference that points to the object. This is where the left side of the equals sign in the code we wrote earlier comes into play.

Employee michail

So, Java doesn’t let us interact directly with memory or manage objects ourselves. However, for practical reasons, it allows us to create a reference that points to the object we’ve created. In our example, this reference is the name michail.

While we handle the reference (michail), Java manages the actual object that the reference points to.

But what does Employee before the reference mean?

Every variable we create in Java has a data type, and the same applies to references. The difference is that here, instead of a primitive data type (like int, double, etc.), we use a data type that’s a class.

Simply put, by declaring the reference michail as type Employee, we’re saying that it will behave like an Employee — meaning it will have all the properties we defined as variables in the class.

Could there be a case where we create an object from one class but want it to behave like it was created from another? Yes, there is—that’s called polymorphism. But it’s too early to dive into that just yet.

Let’s go back to the line of code we wrote and recap what we’ve covered so far. We called the constructor of the Employee class to create a new object. Then, we declared a reference that points to this object and said that the reference will behave like an Employee.

What does that mean? It means that when we write michail. (michail followed by a dot) in the next line of our program, a list of variables will appear—these are the variables whose values we can set for that specific object.

So, for this particular object, we set the following values:

EmployeeDemo.java

package com.example;


public class EmployeeDemo {

public static void main(String[] args) {

Employee michail = new Employee();

michail.AFM = 12345;

michail.department = "IT";

michail.employeeId = 100;

michail.name = "Michail Kassapoglou";

michail.salary = 10000;

}

}


Here, we should mention two points.

First, many programmers casually refer to the variable michail as an "object" when talking with colleagues. For example, you might hear someone say, “I’m creating an object called michail.” Technically, this isn’t accurate, but since they understand the theory—just like you do now—they say it this way for simplicity.

Second, both the Employee class and the EmployeeDemo class are in the same package. So, by default, the Employee constructor looks within that same package when it’s called and finds the Employee class there to create one or more objects. However, they don’t have to be in the same package—that’s a topic we’ll cover in future lessons.

Our program is almost ready; the only thing left is to print out the information for the employee michail that we just created. So, the final form of our code looks like this:

EmployeeDemo.java

package com.example;


public class EmployeeDemo {

public static void main(String[] args) {

Employee michail = new Employee();

michail.AFM = 12345;

michail.department = "IT";

michail.employeeId = 100;

michail.name = "Michail Kassapoglou";

michail.salary = 10000;


System.out.println("Your name is " + michail.name +

" and your employee number is " + michail.employeeId);

}

}

Output

Great! We’ve created our first complete object-oriented program that uses objects!

One last question I want to answer, since you might have wondered already, is: When does the garbage collector delete objects? We create them, but when are they deleted?

Basically, what the garbage collector checks in general is whether there are objects in memory that no longer have any references pointing to them. If it finds objects without any references, it will clean up (delete) those objects within a short period of time.

We can trigger this process ourselves by simply assigning the value null to the reference—that is, by writing:

michail = null;

Finally, if we want to change the value of any variable, all we have to do is write:

michail.salary=20000

Let’s take a look at one last program that includes everything we’ve talked about so far:

EmployeeDemo.java

package com.example;


public class EmployeeDemo {

public static void main(String[] args) {

Employee michail = new Employee();

michail.AFM = 12345;

michail.department = "IT";

michail.employeeId = 100;

michail.name = "Michail Kassapoglou";

michail.salary = 10000;


System.out.println("Your name is " + michail.name +

" and your salary is " + michail.salary);

michail.salary = 20000;

System.out.println("Your name is " + michail.name +

" and your new salary is " + michail.salary);

michail = null;

}

}

Output

Don’t forget to make a small donation so that this blog can grow even more and offer more features for delivering free online lessons.


full-width

Post a Comment

0 Comments