Classes and objects are the heart of Object-Oriented Programming. In this chapter, we will delve into the definition of classes and the creation of objects in Java, and how these concepts can be used to build structured and efficient applications.
# Defining a Class
A class is a model, a blueprint for creating objects.
It defines the attributes (characteristics) and the methods (behaviors) that its objects will have.
public class ClassName {
// Attributes (Fields)
DataType attribute1;
DataType attribute2;
// Constructor(s)
public ClassName(DataType attribute1, DataType attribute2) {
this.attribute1 = attribute1;
this.attribute2 = attribute2;
}
// Methods
public ReturnType methodName(parameters) {
// Method body
}
}
# Attributes (fields)
They are the characteristics or properties that each object of that class will have. For example, a car can have attributes like brand, model, and color. Attributes can have different access levels (public, private, protected) that determine from where they can be accessed and modified.
# Constructor
It is a special method that is called when an object of that class is created. Its job is to initialize the object's attributes. The constructor's name is always the same as the class name, and it does not have a return data type.
There can be more than one constructor in a class, each with different arguments, which is known as "constructor overloading".
An object is an instance of a class, which is created by invoking the constructor.
ClassName object1 = new ClassName(valueForAttribute1, valueForAttribute2);
This process is called "instantiation" and the created object has its own set of attributes and methods defined in the class.
Once we define a class, we can create as many objects as we need from it.
# Destructor
Some languages use destructors, which are invoked when the object is no longer used, and within them, memory is freed.
In the case of Java, it is not necessary since the JVM has the Garbage Collector, which automatically takes care of cleaning memory by deleting objects that are no longer used.
# Methods
Methods are functions defined inside a class. They describe the actions that an object of the class can perform. They can perform operations or return information about the object. For example, a car can start, brake, or accelerate.
# Example 1
We are going to create the 'Book' class to show how classes and objects are defined in Java.
Each book will have attributes like title, author, and number of pages, and methods for reading and showing book information.
public class Book {
// Attributes
private String title;
private String author;
private int numberOfPages;
// Constructor
public Book(String title, String author, int numberOfPages) {
this.title = title;
this.author = author;
this.numberOfPages = numberOfPages;
}
// Method to read the book
public void read() {
System.out.println("You are reading " + title + " by " + author);
}
// Method to show book information
public void showInfo() {
System.out.println("Title: " + title + ", Author: " + author + ", Pages: " + numberOfPages);
}
// Getters and Setters
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(int numberOfPages) {
this.numberOfPages = numberOfPages;
}
}
// Creating an object of the Book class
Book myBook = new Book("One Hundred Years of Solitude", "Gabriel García Márquez", 471);
myBook.read();
myBook.showInfo();
Book is a class with private attributes (title, author, and numberOfPages) and public methods to interact with those attributes.
The read method simulates the action of reading the book, while showInfo provides a general description of the book.
The getTitle and setTitle methods are examples of "getters and setters" that allow access and modification of private attribute values in a controlled and secure way. You cannot access the attributes directly (because they are private), so these methods are used.
# Example 2
In this case, we are going to create a Fraction class, in which we encapsulate the functionality of a fraction.
public class Fraction {
// attributes
private int numerator;
private int denominator;
// methods
public void product(Fraction x, Fraction y) {
numerator = x.numerator * y.numerator;
denominator = x.denominator * y.denominator;
}
public double toReal() {
return (numerator / denominator);
}
public boolean equals(Fraction x) {
return (numerator * x.denominator == denominator * x.numerator);
}
}
We see the case of the product; it is multiplying two Fractions but does not return anything; it is assigning it to a third object, the current object, also called this, a reference to the instance itself.
// z, v and w must be of type Fraction
z.product(v, w);
In some languages like C#, there is the concept of a Property (Property), which can be similar to getters and setters but can also refer to attributes that do not exist (basically, they execute actions).
class Student
{
private string _name; // attribute
public string Name // property
{
get => _name;
set => _name = value;
}
}
# Conclusions
Classes and objects are fundamental and form the basis of object-oriented programming.
Understanding how they are defined and used is the first step. As you progress, you will find yourself designing your own classes and creating complex objects that interact with each other to solve real problems in an elegant and efficient way.