OOPs Concepts in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

OOPs or Object-Oriented Programming is a programming approach that centers on organizing a program around its data and well-defined interfaces, with the aim of making code more closely aligned with the real world. This is achieved by using objects in a programming language.

The main purpose of OOPs programming is to implement ideas and solve real-world problems using classes, objects, inheritance, polymorphism, and abstraction. Some of the most popular OOP languages include Java, C++, and Python.

What is OOPS in Java?

OOPs can be defined as:

A modular approach where data and functions can be combined into a single unit known as an object. It emphasizes data and security and provides the reusability of code. Using OOP, we can resemble our code in the real world.

List of Java OOPs Concepts

The following are the concepts in OOPs :

Well, there are a lot more concepts but the above concepts play a pivotal role in the world of OOPs. Let us understand them in detail. We will try to stick to the above example of the Flight management system for comprehending the concepts in detail.

What is Class in Java OOPs?

A Class is a collection of similar types of objects. It is commonly known as the 'blueprint of an object'. It is a template that describes the kinds of state and behavior that the object of its type support.

  • Class is a user-defined data type. Also, it doesn't occupy any memory.
  • It is composed of name, attributes, and methods. Access Modifiers(public, private, default, protected) are used for having limited or public access to that class so that it can be used by other programs in Java.
  • We create individual objects using class.

Class in Java OOPs

In our example, we can create a class known as "Plane" which will be its name. It consists of the attributes/fields and methods that each plane will have.

We can have the following attributes :

  • plane_number
  • total_seats
  • airline_class
  • pilot_name

Our "Plane" class can contain the following methods to use the above attributes

  • seatAvailability()- this checks how many seats are available or vacant on that plane.
  • selectClass()- lets you choose the class in which you want to travel- eg. business class or economy class.

In short, the "Plane" class is a blueprint that represents a plane in a flight management system and we have to create it to represent a real-world entity.

Syntax:

But before diving deeper into the sea of OOPs, let us get acquainted with some terminologies.

Member Functions- The functions are written inside a class are known as member functions.

Instance variables- Variables that are declared within the scope of the class.

What is an Object in Java OOPs?

As we have discussed above, Objects are the building blocks of OOP. A Java program is mostly a collection of objects talking to other objects by invoking each other’s method.

At a run time, when JVM encounters the “new” keyword, it will use the appropriate class o make an object which is an instance of that class. That object will have its state and access to all of the behavior defined by the class.

  • Objects are real-world entities which have a certain state and behavior.
  • Objects are commonly known as an 'instance of a class'.
  • In our example, we created the class "Plane". So now, we will create objects from the same class. Each object will have the attributes and methods defined in the class. If we want to create an object of class "Plane" , we use the following syntax.

Syntax:

So this P1 object will contain its characteristics like its number, total seats, plane class(business, economy, etc.), and pilot. Creating another object of class "Plane" will give it all the attributes that were defined in that class.

  • Objects interact with each other and share information. This technique is termed Message Passing.
  • Objects are allocated memory space and address too.

The following figure illustrates the relationship between objects and classes.

relationship between objects and classes in java oops

The figure shows that the class Plane acts as a template to create objects which contain the attributes of the class(Plane).

Four Pillars of OOPs in Java

The following are the basic principles of OOP in Java. They are known as the principles as the entire OOP lays its foundation on these principles.

  • Inheritance

  • Polymorphism

  • Abstraction

  • Encapsulation

An easy way to remember OOPs principle is by remembering the sentence- I ate A PIE.(Abstraction, Polymorphism, Inheritance, Encapsulation)

What is Inheritance in Java OOPs?

Inheritance is a mechanism of deriving one class from another. It allows the derived class to inherit features from a parent class, the features include (fields and methods). The parent class is also known as the superclass or base whereas the derived class is known as a subclass or child class.

  • Inheritance is a property of OOPs in which member functions and data members of one class can be used by another class.
  • Reusability of code can be achieved because of inheritance. If we want to create a class that already has some common methods which we want to define within another class, we can use the already existing class as a base class or a parent class and then inherit from it.
  • Hence the code can be reused as we don't need to write the same piece of code again and can use it in the derived class or child class.
  • Base class- a class from which member functions and data members are used by another class.
  • Derived class- a class that uses the properties of the base class and can also add its properties.

In our example, we created a class "Plane" which contained attributes like plane_number, total_seats, airline_class, and pilot_name. All the planes are of the sub-type of class "Plane" and they have common attributes mentioned above.

So in addition planes have their distinct attributes like luxury_arrangements, food, and air hostess. So instead of defining the common properties again, we can only define the distinct properties in the new class and inherit the common properties from the base class.

Types of Inheritance :

  • Single
  • Multilevel
  • Hybrid
  • Hierarchical Inheritance in Java OOPs

The above image shows various inheritances and their syntax.

What is Polymorphism in Java OOPs?

As the name suggests, it means many forms. It is the ability to create a function, variable, or an object that has more than 1 form. The concept of polymorphism is expressed by 'one interface, many methods'. It is one of the Principles of OOPs.

Two types of polymorphism in java :

  • Compile-time : It is also known as static or early binding. The binding is performed during compilation time.
  • Run time : It is also known as dynamic or late binding. The binding occurs during runtime, depending on the type of object.

The two types of polymorphism are achieved in java by :

  • Overloading : In Java, it is possible to create methods that have the same name, but different parameter lists and different definitions. This is called overloading.
  • Overriding : It is a technique of re-implementing or re-writing a method of a superclass in its subclass.

Example- In our example, we had created a class known as "Plane" and one of the methods was seatAvailability() which returns the number of seats vacant in a plane. We created another derived class "Jet" which will contain the attributes of the Plane class. So, if the Jet Class Object calls the seatAvailability() method, it will return the number of seats vacant in it.
Other than that, the jet can also be used as a private jet when some dignitary books it. At that time the Jet has many new features and it no longer required to use the seatAvailability() method as the entire jet belongs to the dignitary. Here, the Jet has one interface and many forms.

Polymorphism in Java OOPs

This not only aids in code reusability as we don't have to write the same methods again but also in reducing the complexity by allowing the interface to be used for a general-purpose of action.

What is Abstraction in Java OOPs?

The literal meaning of abstraction is to focus on the essential details rather than the irrelevant things. In OOPs, the same concept holds. It is the process of representing the essential features and hiding the implementation details.

  • In Java, class is used for abstraction. Hence, it is also referred to as an 'abstract data type'.

Example- Consider the example of a bike. While driving, do you ever wonder what mechanism is used to operate the bike, or how does the gearbox work?
The answer is No! This is what abstraction is.
We only focus on the external details like pressing the accelerators, brakes, etc. This is the concept of abstraction.

concept of abstraction

What is Encapsulation in Java OOPs?

Encapsulation is the process of binding data and methods together in a single unit. This is done to protect the data from outside interference and to camouflage the implementation from the rest of the program.

  • In encapsulation, data in the class is hidden from other functions and classes. The data is inaccessible by other classes and can be accessed only by that class in which it is declared. Hence, it is also known as 'Data Hiding'.
  • In Java, class forms the basis of encapsulation.

Example- In our example, we created the class "Plane" and defined an attribute plane_number which was a data member(instance variable) of the class. If we want that data member to be confined to that class only, we have to use a keyword known as "private" which is an access specifier. The data member should be preceded by the access specifier.

Example

Explanation- We created a private data member plane_number which can only be accessed and changed by that class itself and no other class, it is the process of encapsulation.

Other OOP Concepts in Java

We have discussed all four principles of OOP, i.e., Inheritance, Polymorphism, Abstraction and Encapsulation. Now we will be discussing other core concepts of OOP that play vital role in Java programming.

What is Coupling in Java OOPs?

Coupling is a term that is used to denote the degree of dependency of one class on another. It shows if two classes are inter-related and if they require each other to complete a function.

There are 2 types of coupling :

  • Tight coupling- If two classes are dependent on each other, they follow tight coupling. The word tight refers to their coupling analogy which means they are bound together tightly. If the changes are made in the parent class, it gets reflected in the child class too.
  • Loose coupling- If two classes are independent of each other, it is referred to as loose coupling. It is more advantageous as it reduces code maintenance as both classes are not dependent on each other. Changes made in one class do not affect the other class. It can be achieved by making an interface.

two types of coupling in java OOPs Example- In our example, we have created a class "Plane" and one more sub-class "Jet" which was inherited from the parent class.

Jet mainly depended only on Plane and any changes made in Plane class, would be reflected in the Jet class. This is not desirable as changes made in Plane will be reflected in the Jet class and will not be necessarily as we want it to be in the Jet class. These two classes are said to be tightly coupled.

Similarly, we can make a "Plane" class that points to an interface, which can then be implemented by the "Jet" class. Any class that implements the interface can thus satisfy the dependency of the "Plane" class (that is the base class) without having to change the class. Here any changes made in the base class won't affect the derived class.

What is Cohesion in Java OOPs?

Cohesion is used to describe how well a single class is designed. With this concept, it is expected that a class should be well-designed and should have a clear purpose. A class with a precise purpose has a better degree of cohesion. It not only facilitates easy maintenance but also reusability of code.

There are two types of cohesion :

  • High cohesion
  • Low cohesion

High cohesion- When a class is well defined it is said to have high cohesion. More cohesiveness is the advantage that it carries.
Low cohesion- When a class is not well defined, it is said to have low cohesion. Such classes are difficult to maintain.

Example- In our example, we had created a class "Plane" which defined all the methods of that class. Instead of writing all the methods in a single class, we will write methods in separate classes. This will make the program more cohesive and the classes will have a well-defined purpose.

two types of cohesion in java OOPs

What is Association in Java OOPs?

Just like the literal meaning of the word, it means to 'establish a connection. We all have learned about various types of relationships between sets in Mathematics. They were :

  • One-to-one
  • One-to-many
  • Many-to-one
  • Many-to-many

The same concept is used in programming to describe the relationship between two separate classes.

  • Association represents HAS-A relationship.
  • These classes are connected with the help of objects.
  • In our example, if we create a class "Airport" to represent the airport and another class "Plane" which represents planes in an airport, we can show their association in the following way.

Association in Java OOPs Here we can say that Airport "HAS-A" Plane.

  • There are two sub-parts of Association-
    • Aggregation
    • Composition

The following diagram shows the relationship between Association, Aggregation, and Composition.
sub parts of Association in Java OOPS

What is Aggregation in Java OOPs?

  • It is used to represent a one-way relationship between two objects.
  • In Java, aggregation is also used to establish a HAS-A relation.
  • When one class contains a reference of another class, it is called Aggregation i.e., one class object depends on the object of another class.
  • In aggregation, only one class depends on the other, i.e. it is unidirectional. Like an Airport has Planes but Planes cannot have an airport. We can say that an Airport "HAS-A" plane, Jet etc.

What is Composition in Java OOPs?

  • It is a restricted form of aggregation.
  • If an object contains another object and if they are interdependent, they cannot exist without one another.
  • It is done by creating an instance variable that refers to another object.
  • In our example, we had created a class "Plane" which had a derived class called "Jet". Here Jet had the attributes defined in the base class Plane. If we delete the Plane class object, the Jet class object also gets deleted as the Jet class was dependent on the Plane class.

OOP Features in Java

  • Emphasizing data more rather than functions.
  • Reducing the complexity of programs by dividing them into smaller chunks called Objects.
  • Enhanced security by securing data and functions.
  • Code reusability. Code reusability can be achieved through inheritance. If we want to create a class that already has some common methods which we want to define within another class, we can use the already existing class as a base class and then inherit from it.
    Hence the code can be reused as we don't need to write the same piece of code again and can use it in the derived class or child class.
  • It follows the Bottom-Up approach to programming. In this, we first identify all the basic parts (classes) of the system and define the properties and actions of these parts. Next, we create multiple instances of these parts and allow them to interact with each other

Best Practices for OOPs Concepts in Java

  • A class should have a single and well-defined purpose(cohesion).
  • It is too important to use meaningful names for classes objects etc. This leads to proper documentation of the code.
  • Always write methods in such a way that the number of arguments is as minimal as possible. This makes code easier to read.
  • Whenever we use the OOP concept, the use of global variables or objects needs to be avoided. We should follow the principles of encapsulation.

Benefits of OOPs in Java

  • The benefit of code reusability.
  • Easier to co-relate with the real-world.
  • Generation of a secured program.
  • Convenient to solve complex problems.
  • Easy to maintain the software complexity.
  • Multiple instances can be generated for an object.

Imagine A World Without OOPs

Would you like to live in a world with a lesser resemblance to real-life objects which makes it tough to correlate with the real-world, lack of security, more complexity, lesser flexibility, and low reusability? The answer is NO. The same scenario applies to programming. OOP provides all contrary features as mentioned above.

Conclusion

  • OOPs stands for Object-Oriented Programming which is a programming paradigm designed for enhanced security, and better code organization leading to long-time developer productivity.
  • Objects are the basic elements of OOPs.
  • Classes are blueprints or collections of similar types of objects.
  • Inheritance is the process by which objects can link and share their properties within objects of a class.
  • Encapsulation is the process of binding data and methods together in a single unit.
  • Abstraction is the process of representing the essential features and hiding the implementation details.
  • Polymorphism is the ability to create a function, variable, or object that has more than 1 form.
  • Coupling is a term that is used to denote the degree of dependency of one class on another.
  • Cohesion is used to describe how well a single class is designed.
  • Association is used in programming to describe the relationship between two separate classes.
  • Aggregation is used to represent a one-way relationship between two objects.
  • Composition is also used to establish a HAS-A relation.

FAQs

Q.. What are the 4 OOPs concepts in Java?

A. The 4 main OOPs concepts in Java are- Encapsulation, Polymorphism, Inheritance and Abstraction.

Q. Why is Java called an OOP language?

A. Java is called an OOP language as everything in Java is an object. Programs are stored inside classes. Without classes and objects, it is impossible to write a program in Java. In addition to this, it provides features like Encapsulation, Polymorphism, Inheritance, and Abstraction which makes it an Object-Oriented language.

Q. Why is OOPs important?

A. OOPs is important as-

  • It ensures the security of data by data hiding, encapsulation, and abstraction.
  • It makes our code resemble the real world.
  • It allows the reusability of code by inheritance.
  • It reduces the complexity of programs by providing the feature of polymorphism where one interface can be used for many purposes.
  • It divides the program into smaller chunks called objects which form the foundation of OOPs.
  • It does not allow data to flow freely as it happens in Procedural-Oriented Programming.
  • More emphasis is given on data rather than functions.

Q. Which programming languages are OOP?

A. Simula was the first semi Object-Oriented Programming language. But, SmallTalk is the first complete Object-Oriented Programming language.
Other OOP languages include- Java, C++, Python, JavaScript, Kotlin, C#, etc.

Q. Is Java a pure OOP language?

A. No. Java is not a pure OOP language as it supports primitive data types like int, char, byte, etc. which are not objects. In OOP, it is expected that everything inside a program gets treated like an object.
Another reason is the 'static' keyword. In OOP, everything is accessed using message passing(how objects communicate). Java contains static variables and methods which can be accessed directly without using objects. That means when we declare a class as 'static' then it can be referenced without the use of an object. This defies the OOP concepts.

See More: