Introduction to OOP in Java
In this article, we lay the foundations for covering object-oriented programming by first going through classes, objects, access modifiers and fields.
Object-oriented programming (OOP)
The main reason OOP was invented was that programmers were looking for a way to model real-life objects in the software they were building.
Real-life objects have characteristics and behaviors. In Java, we use classes and objects as the foundational building blocks for implementing OOP. In this article, we explore classes and objects in detail.
Classes and objects
Classes can be looked at as independent self-managing modules with characteristics and behaviors.
An object is an instance of such a module, and a class is its definition.
The predefined data types in Java are classes themselves eg int, char, boolean, float, etc.
Classes are user-defined data types. However, we can use these basic data types to create our own class. In addition, classes can contain functions (behaviors) that would be available during object creation.
Let's consider a car.
A car has various characteristics such as model, manufacturer, engine capacity, year, etc. It also has several behaviors such as start, stop, accelerate, refuel, park, etc. These can all be modeled using OOP.
In Java, these characteristics are referred to as fields or member variables.
The functions (behaviors) are known as methods.
Classes are also very useful in compartmentalizing the code of an application. Different components could become separate classes that can interact through interfaces. These ready-made components will also be available for use in future applications.
The use of classes makes it easier to maintain the different parts of an application since it is easier to make changes in classes.
This makes your code simple, clean, modular, and reusable.
Class Definition/Implementation
This is how you declare a class in Java.
//The Structure of a Java Class
class Car { // Class name
// Fields
int engineCapacity;
int numberOfTyres;
int fuelCapacity;
String manufacturer;
// Methods
void start(){
...
}
void stop(){
...
}
void accelerate(){
...
}
}
The class
keyword tells the compiler that we are creating our class.
Note: All words in a class name always begin with a capital letter. The Java file contaning the class
should also have the same name as the class
name. In this case, the Java file would be named Car.java
.
Object creation
Code snippet:
class Car{ // Class name
...
// Main method
public static void main(String args[]) {
Car car1 = new Car(); // Create an object called car1
}
}
We use the new
keyword to create the object.
Access Modifiers
As part of Java's robustness and strong security features, we can restrict how field members and methods are accessed. We can do this through access modifiers. We have 3 different access modifiers:
Public
Private
Protected (We will cover the protected access modifier when we talk about inheritance).
Private
A private member cannot be accessed directly from outside the class. The aim is to keep it hidden from other users and other classes. It is a popular practice to keep the fields private since we do not want anyone accessing our data directly. We can make members private using the keyword private
.
Code snippet:
class Users {
// Private fields
private String userName;
private String email;
private String password;
...
}
We have a Users
class that makes sure that primary user data is private and cannot be accessed outside the class.
Public
Public members can be directly accessed by anything which is in the same scope as the class object.
Functions are usually public as they provide the interface through which the application can access our private members.
Public members can be declared using the keyword public
.
Code snippets:
class Users {
private String userName;
...
public int getUserName(){
return userName; // The private field can now be directly accessed
}
}
class Users {
private String userName;
public int getUserName(){
return userName;
}
class Main{
public static void main(String args[]){
Users user = new Users(); // Create an object called user
user.getUserName(); // user can access the username
user.getUserName = "Vivian"; // This would cause an error since username is private
}
}
Fields
We have 3 types of fields:
Static fields
Non-static fields
Final fields
Static field
A static field resides in a class. All the objects we create will share this field and its value. It is accessible before an instance of that class is created. We define it using the static
keyword.
Code snippet:
class Car {
// Static fields
static String manufacturer;
static int engineCapacity;
...
}
We don’t need an object of the class to access static fields. We can access the static fields of a class by writing the class name before the field.
Code snippet:
class Car {
// Static fields
static String manufacturer = "Toyota";
static int engineCapacity = 3000;
}
class CarDemo {
public static void main(String args[]){
// Static fields are accessible in the main method
System.out.println(Car.manufacturer);
System.out.println(Car.engineCapacity);
}
}
Non-static field
Non-static fields are located in the instances of the class (objects). Each instance of the class can have its own values for these fields. They are also known as instance variables. They are created during run time. Hence, non-static fields cannot be accessed until an instance of that class is created.
Code snippet:
class Car {
// Non-static fields
String manufacturer = "Ferrari";
int engineCapacity = 4500;
}
class CarDemo {
public static void main(String args[]){
Car car1 = new Car(); // Create an object called car1
System.out.println(car1.manufacturer);
System.out.println(car1.engineCapacity);
}
}
Final fields
A final field cannot have its value changed once it is assigned. We can make a field final by using the keyword final
.
Code snippet:
class Car {
// Final field
final int powerSupply = 450;
}
class CarDemo {
public static void main(String args[]) {
Car car1 = new Car();
car.powerSupply = 500; // Compiler error! This value can't be reassigned
}
}
Conclusion
We now have laid the foundations for OOP in Java by defining some key terms and concepts. Next, we will dive deeper into methods. Stay tuned 👀