Object-oriented programming (OOP) is at the core of Java. The central idea is simple: Organise your programs in a way that mirrors the way objects are organised in the real world. OOP concepts in Java is an important feature of Java, so we would understand its basic principles first.
OOP Concepts in Java
There are four main OOP concepts in Java. These are:
Abstraction
It is used to manage the complexity of a system. By this property, we can provide only the essential features of an object to the user without including the background details or explanations. For example: People do not think of a car as a set of tens or thousands of individual parts. They think of it as a well-defined object with its own unique behavior. This abstraction allows the people to use the car easily ignoring the complexities of the parts that make a car.
Encapsulation
It is a principle of binding or wrapping together code and the data it manipulates as a single unit. It keeps both the code and data safe from outside interference and misuse. It acts as a wrapper and access to the code and data inside the wrapper is tightly controlled through a well-defined interface.
In Java, encapsulation is in the form of classes. A class defines the structure and behavior (data and code) that will be shared by a set of objects. Data defined by a class are referred to as member variables and the code that operates on the data is referred to as member methods.
Inheritance
The word ‘Hereditary’ refers to the process of inheriting certain characteristics from your parents or ancestors. In the same way, inheritance is the process by which one object acquires the properties of another object. For example: a Lion is a member of the classification cats, which in turn is a member of mammal class, which is under the larger class animal.
A class that is derived from an existing class is called a subclass or derived class whereas the class from which a subclass is derived is called a superclass or base class. The common features of all the classes are defined once in the base class. The sub classes derive the functionality of their base classes automatically.
Inheritance also allows code reusability. Reusability is the process of using existing code for new programming problems by adding some new features and capabilities to that code, without modifying its functionality in any manner.
Polymorphism
Poly means many and morphism means forms. Thus, Polymorphism means more than one form. It provides a way for an entity to behave in several forms i.e. “one interface and multiple methods”. This means that it is possible to design an interface which groups related activities. This helps to reduce complexity as it allows us to use the same interface to specify a general class of action. For example: The function Area can be used to represent the area of a rectangle, a square, or a circle.