OOP concepts in Java: The essence of Java programming

Object-oriented programming in Java

Imagine that you are a librarian, and you want to create a Java application to keep a track of all library resources such as books, journals, and newspapers. Would you prefer to write separate code for each one of these or would you like to use reusable code? If you chose the latter, then OOP can help you with that.

What is OOP?

Object Oriented Programming (OOP) is a programming paradigm that uses the real-world concepts of objects and classes. 

Objects are modelled on real-life entities such as a book, a house, or a scooter. They have attributes such as color, model, and price, that is known as the state of the object. These objects are capable of performing certain functions such as driving, accelerating, etc. that are referred to as methods in Java terminology. 

Different objects can share similar attributes and functions. For example, all scooters have some common properties such as they all have a color and price, and all of them can perform functions like driving, stopping, etc. This means that they can be created using a similar template. This template or blueprint is called a class in Java. So, for this example, we can create a class called Scooter.

Now that you have a basic understanding of classes and objects, let’s dig deeper into all the OOP concepts.

OOP concepts in Java

1. Classes – Every Java program begins as a class that can contain fields, constructors, and methods. Here is an example of how to create a class in Java –

class College { // class open

public String department; //these are called fields

public int noOfStudents;

public College (String departmentName, int strength) {
}

} // class closed

In the example above, the class has been declared by using the keyword class. The first letter of the class name College has been capitalised, which is a naming convention in Java. The name is followed by a curly brace that is closed when the class is closed. The variables department and noOfStudents are called fields or field variables because they have been declared outside a method. 

2. Object – An object is an instance of a class, which is created using the keyword new. For example – 

College jamia = new College();

The new keyword allocates memory to the object during runtime. jamia is an instance/reference variable that stores the location of this newly created object in heap memory.

Objects in Java

If you do not create an instance variable for it, the object can still be created like this –

new College();

However, you will not be able to use this object. 

To assign values to the variables department and noOfStudents, you can follow the following syntax – 

jamia.department = “Hindi”;

jamia.noOfStudents = 30;

You can also assign these values through getter and setter methods, which is the preferred way because it makes the data more secure. The setter method is used to set the value. For example –

public void setDepartment (String d) {

this.department = d;

}

Here, we have used the return type as void because the method does not return any value.

The getter method is used to return a value. For example –

public String getDepartment () {

return department;

}

This method has the String return type, which means it returns a String value. 

Now, if you want to initialize the variables again, you can do it in the following way –

College jamia = new College();

jamia.setDepartment(“Hindi”);

To print this value, you can use the getter method –

System.out.print(jamia.getDepartment() );

3. Constructors – While declaring an object, the new keyword is followed by a call to the constructor. 

College jamia = new College();

In the above example, new College() is the constructor. A class can have any number of constructors. The most basic is the default constructor that does not return any value. Here’s how it looks like inside a class –

class College {

String department;

int noOfStudents;

public College() { //default constructor

}

To create a constructor, you must follow some ground rules –

i. Class and constructor(s) share the same name.
ii. A constructor is like that friend who never returns anything. You can, however, add values inside parameters with a constructor. For example –

Scooter activa = new Scooter(60000);

This is called a parameterized constructor. It will assign a value of 60000 to an instance variable. Here’s how the constructor looks like inside the class –

class Scooter {

int price;

String model;

public Scooter(int p) {

this.price = p; // this is a keyword that refers to the current object. So, you are assigning value to the price instance variable for the current object

}

You can also create multiple constructors with different parameters. This concept is called constructor overloading. So, in the above example of class Scooter, you can write another constructor –

pubic Scooter(int p, String m) {

this.price = p; 

this.model = m;

}

The java compiler is a smart cookie which will figure out which constructor you have called depending on the values you pass during object declaration. For instance –

Scooter activa = new Scooter(60000, “black”); // this will call the constructor with two parameters

iii. If you are not creating a parameterized constructor, you do not have to create a default constructor.

As you can see, you can use both constructors and setter methods to assign values to instance variables. However, the constructor is used when the values are known to you at the time of object declaration. Setter methods, on the other hand, allow you to set a value at a later stage as well.

4. Inheritance – Have you ever been grateful about a trait that you got from your parents like having your mom’s hair or your dad’s eyes? Because OOP is a paradigm that is largely based on the real-world, this is an important concept in Java as well!

Inheritance is a concept which allows a class to inherit properties of another class. For example, let’s take two classes called Batcycle and Batmobile. Although the two are different in many ways, they have some common properties such as engine, color, and price, and both of them are used for commuting. So, you can create a common class called Vehicle that has these properties and behaviour.

Once you have created the Vehicle class, you can use the keyword extends to inherit the properties of this class. For example –

class Batcycle extends Vehicle

class Batmobile extends Vehicle

Inheritance in JavaYou can use the inherited properties in the following way –

Batcycle bat = new Batcycle;

bat.color = “black”;

bat.engine = “V4”;

Batmobile cat = new Batmobile;

cat.color = “red”;

cat.engine = “V8”;

In the above example, the Vehicle is called the parent or super class whereas Batcycle and Batmobile are called child classes or sub classes. This is called hierarchical inheritance. Other types of inheritance include single inheritance where one class inherits properties of another, and multilevel inheritance, which is multistep inheritance. For example, class BellBottomPants inherits properties of class Pants which has inherited the properties of class Clothes.

Inheritance helps in code optimisation by allowing us to reuse code.

5. Polymorphism – While inheritance allows class(es) to inherit fields and methods of another class, polymorphism makes it possible for one class to use the methods of another class. This is called runtime polymorphism, and it takes place in the form of method overriding. This means that all the classes use the same method signature, but can differ in their code. For example –

class Vehicle {

String color;

String model;

public void commute() {

System.out.println(“All vehicles are used for commuting”);

}

}

class Batcycle extends Vehicle {

String ownerName;

public void commute() { //using the same method signature as the Vehicle class

System.out.println(“Only two passengers can commute on a Batcycle”);

}

}

When the program is executed, the JVM figures out which method to run. In the example below, it will run the commute() method of the Batcycle class.

Batcycle b = new Batcycle;

b.commute();

The other type of polymorphism in Java is called compile time polymorphism, and you can use this through method overloading. In this type, methods with the same name can take many forms. For example –

public void calculateStipend() { //it does not return a value

//code

}

public int calculateStipend(int a, int b) { //it returns an integer value

//code

}

The compiler decides which function to call. Compile time polymorphism is primarily used to enhance the readability of the code.

6. Encapsulation – The subtle art of data hiding in Java is called encapsulation. It involves wrapping the data in class variables with its functions. This can be achieved by declaring the class variables as private and using getter and setter methods to initialize them. For example –

class JavaBasics {

private int num1;

private int num2;

private int difference;

public int getTheDifference() {

this.difference = num1 – num2;

return difference;

}

public void setValues(int n1, int n2) {

if(n1>n2) { //a setter method can also help you in controlling the values the variables accept

this.num1 = n1;

this.num2 = n2;

}

else {

System.out.println(“The first number should be greater than the second”);

}

}

Now, let’s create an object of class JavaBasics and call these methods.

class Test {

JavaBasics obj1 = new JavaBasics();

obj1.setValues(50, 40); //you cannot use obj1.num1 = 50 or obj1.num2 = 40 because they are not public variables that can be accessed directly outside the class

obj1.getTheDifference();
}

In the example above, the private access modifier and the getter and setter methods control the scope of the data stored and used in the class. This makes the data more secure which makes encapsulation a common practise among Java developers.

6. Abstraction – To implement inheritance in Java, we can create a superclass whose objects cannot be created. These are called abstract classes, and they can also contain methods with no body, which are called abstract methods.This process is called abstraction, and it gives a structure to the objects of the subclasses without showing unnecessary information. For example –

abstract class Language {

int numberOfSpeakers;

public abstract void printNumber(); //abstract methods are closed with a semicolon

public void getNumber(int n) {

this.numberOfSpeakers = n;

}

These were the key OOP concepts in Java. Now that you know the basics of OOPs, you can put them into practise by creating an app in Internshala’s Core Java training! You can use the coupon code BLOG10 to get a discount of 10%.

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *