OOPs Concepts in Java: Encapsulation, Abstraction, Inheritance, Polymorphism

OOPs Concepts in Java: Encapsulation, Abstraction, Inheritance, Polymorphism

25 Sep 2024
Intermediate
7.69K Views
22 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate (2024)

OOPs Concepts in Java: An Overview

OOP concepts in Java are one of the most important Java features in the development field, and they were created in 1970. Let's understand the OOP concepts in Java in this Java tutorial. For practicals and in-depth understanding, enroll in our Full Stack Java Course section.

Read More: Best Java Developer Roadmap 2024

What is the OOPs Concept?

Object-oriented programming is one of the fundamental concepts of programming helping developers to bind functions and data together with the help of objects and classes. The OOPs concept in Java assists the programmers in controlling and accessing the data and implementing this to improve the readability and reusability of the code. In Java, every class has some objects. Every object has some methods and properties associated with it. Combining them will build the structure of object-oriented programming.

The OOP concepts in Java depend on four pillars, which are:

  1. Abstraction
  2. Inheritance
  3. Encapsulation
  4. Polymorphism

Read More - Advanced Java Interview Questions

What are Classes and Objects in Java?

  • Classes in Java are "local entities" that do not require any memory space without the object.
  • It is a blueprint of Java programming. The class keyword is used to declare a class such as objects, methods, variables, etc. that are situated inside the class.
  • For instance, an architectural drawing of a building is called a blueprint as well as it can be called a "class" and the building that is created according to the blueprint is called an "object".
  • The class represents the working and structure of an object by using variables and attributes of the data and the method or the member functions.
  • Data attributes assist in defining the member functions in Java.

What are Classes and Objects in Java?

Syntax


<access-modifier> class <className>
{
 // data attributes;
 // member functions()
}

A class consists of some elements that are

  • Class: It defines the particular class
  • Access Modifiers: It defines if the class should be "public", "private", "package-level (default)" or "protected".
  • Class Name: Give a name to the class
  • Superclass: It mentions the name of the superclass if there are any
  • Interface: Mentions the name of the super interface if there is any
  • Body: It represents the body of the class with {} these curly braces.

Example illustrating Classes and Objects in Java


class MyClass { // The class
    // Attributes (instance variables)
    public int num;
    public String string;
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass(); // Create an object of MyClass

        // Access attributes and set values
        obj.num = 25;
        obj.string = "Welcome to ScholarHat";

        // Print attribute values
        System.out.println(obj.num);
        System.out.println(obj.string);
    }
}

Output

25
Welcome to ScholarHat 

Read More: What is Class in Java? - Objects and Classes in Java

Fundamental Pillars of OOPs Concept

There are four fundamental Pillars of OOPs Concept in Java, which are

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Fundamental Pillars of OOPs Concept

1.) Encapsulation in Java

  • In object-oriented programming (OOP), encapsulation groups data and methods into a class while hiding implementation-specifics and exposing a public interface.
  • Encapsulation in Java includes limiting direct access by defining instance variables as private.
  • There are defined public getters and setters for these variables.
  • Data validation as well as consistent internal state management within the class are made possible by the use of getters, which obtain variable values, and setters, which make changes.

Example


public class Person {
 private String name;
 private int age; // Constructor
 public Person(String name, int age) {
 this.name = name;
 this.age = age;
 } // Getter for name
 public String getName() {
 return name;
 } // Setter for name
 public void setName(String name) {
 this.name = name;
 } // Getter for age
 public int getAge() {
 return age;
 } // Setter for age
 public void setAge(int age) {
 if (age > 0) {
 this.age = age;
 } else {
 System.out.println("Age cannot be negative.");
 }
 } // Display person information
 public void displayInfo() {
 System.out.println("Name: " + name);
 System.out.println("Age: " + age);
 } public static void main(String[] args) {
 // Create a Person object
 Person person = new Person("Alice", 30); // Access and modify fields using getters and setters
 person.setName("Bob");
 person.setAge(25); // Display person information
 person.displayInfo();
 }}

The 'Person' class in this Java example in the Java Online Editor is defined as having private name and age fields as well as getter and setter methods. It creates an object called "Person," modifies its name and age, and then updates the data displayed.

Output

Name: Bob
Age: 25

Advantages of Encapsulation in Java

  • We can make a class read-only or write-only: for a read-only class, we should provide only a getter method. For a write-only class, we should provide only a setter method.
  • Control over the data: We can control the data by providing logic to setter methods.
  • Data hiding: other classes can’t access private members of a class directly.

Read More - Java Developer Salary

2.) Abstraction in Java

  • Abstraction in Java is achieved through interfaces and abstract classes.
  • 100% abstraction can be achieved using interfaces.
  • Data abstraction involves identifying only the essential characteristics of an object while ignoring irrelevant details.
  • The properties and behaviors of an object distinguish it from other objects of the same type and help classify or group objects.

Example


// Abstract class representing a shape
abstract class Shape {
 // Abstract method to calculate the area of the shape
 public abstract double calculateArea(); // Abstract method to calculate the perimeter of the shape
 public abstract double calculatePerimeter();
}// Concrete class representing a Circle
class Circle extends Shape {
 private double radius; public Circle(double radius) {
 this.radius = radius;
 } @Override
 public double calculateArea() {
 return Math.PI * radius * radius;
 } @Override
 public double calculatePerimeter() {
 return 2 * Math.PI * radius;
 }
}// Concrete class representing a Rectangle
class Rectangle extends Shape {
 private double length;
 private double width; public Rectangle(double length, double width) {
 this.length = length;
 this.width = width;
 } @Override
 public double calculateArea() {
 return length * width;
 } @Override
 public double calculatePerimeter() {
 return 2 * (length + width);
 }
}public class AbstractionExample {
 public static void main(String[] args) {
 // Creating objects of Circle and Rectangle
 Circle circle = new Circle(5);
 Rectangle rectangle = new Rectangle(4, 6); // Using the abstracted methods to calculate area and perimeter
 System.out.println("Circle - Area: " + circle.calculateArea() + ", Perimeter: " + circle.calculatePerimeter());
 System.out.println("Rectangle - Area: " + rectangle.calculateArea() + ", Perimeter: " + rectangle.calculatePerimeter());
 }
}

This Java program in the Java Playground shows the concept of abstraction by defining the abstract classes "Shape""calculateArea()" and "calculatePerimeter()," respectively. 'Circle' and 'Rectangle' are concrete subclasses that derive from 'Shape' and offer particular implementations for these methods to determine the area and perimeter of circles and rectangles. The area and perimeter of objects of type "Circle" and "Rectangle" are calculated and displayed in the "main" method.

Output

Circle - Area: 78.53981633974483, Perimeter: 31.41592653589793
Rectangle - Area: 24.0, Perimeter: 20.0

3.) Inheritance in Java

  • A key component of Object-Oriented Programming (OOP) in Java is inheritance.
  • The attributes (fields) and behaviors (methods) of one class may be inherited by another class.
  • Creating new classes based on preexisting ones is what inheritance is all about.
  • A subclass or derived class derives from another class.
  • The superclass or base class is the one from which the subclass inherits.
  • The properties and methods of a superclass can be used by a subclass.
  • To increase the functionality of the superclass, subclasses can also add additional fields and methods.
  • In Java, inheritance encourages the reuse of existing code and the development of hierarchies of related classes.

Inheritance in Java

There are three types of Inheritance in Java:

  1. Single Inheritance: This is a single level Inheritance with one subclass with the properties of super class
  2. Hierarchical Inheritance:It multiplied one parent class with child classes
  3. Multilevel Inheritance: If there are 3 classes named A, B, and C then class B inherits the properties of class A and class C inherits the properties of class B

Example


// Base class (superclass)class Animal {
 String name; public Animal(String name) {
 this.name = name;
 } public void eat() {
 System.out.println(name + " is eating.");
 } public void sleep() {
 System.out.println(name + " is sleeping.");
 }
}// Derived class (subclass)
class Dog extends Animal {
 public Dog(String name) {
 super(name);
 } public void bark() {
 System.out.println(name + " is barking.");
 }
}public class InheritanceExample {
 public static void main(String[] args) {
 // Create a Dog object
 Dog myDog = new Dog("Buddy"); // Call methods from the base class (Animal)
 myDog.eat();
 myDog.sleep(); // Call a method from the derived class (Dog)
 myDog.bark();
 }
}

The 'Dog' class in the Java Online Compiler inherits from the 'Animal' class to show inheritance in action. The 'Dog' class adds its own method 'bark' and inherits the 'eat' and 'sleep' methods from the 'Animal' class. A "Dog" object called "Buddy" is created in the "main" method, and its methods are used to demonstrate how a subclass can utilize and expand the features of its superclass.

Output

Buddy is eating.
Buddy is sleeping.
Buddy is barking.

Read More: What is Inheritance in Java

4.) Polymorphism in Java

  • A key component of object-oriented programming (OOP) is polymorphism.
  • It makes it possible to carry out a single activity in a variety of ways.
  • One interface or function signature may have many implementations thanks to polymorphism.
  • In polymorphism, the word "poly" refers to "many," and "morphs" refers to "forms," therefore polymorphism simply means "many forms."
  • It supports OOP's flexibility and code reuse.
  • Method overloading and method overriding are frequently used to achieve polymorphism.
  • Removing the underlying implementation details facilitates code maintenance and improves code readability.
  • To achieve dynamic binding, also known as late binding, where the exact method to be executed is determined at runtime, polymorphism is an essential concept.

There are two types of Polymorphism, such as

  1. Compile-time Polymorphism- is used for expressing the overloading in Java programming
  2. Run-time Polymorphism- it is used for expressing overriding.

There are two types of Polymorphism, such as

Example


class Shape {
 public void draw() {
 System.out.println("Drawing a shape");
 }
}class Circle extends Shape {
 @Override
 public void draw() {
 System.out.println("Drawing a circle");
 }
}class Rectangle extends Shape {
 @Override
 public void draw() {
 System.out.println("Drawing a rectangle");
 }
}public class PolymorphismExample {
 public static void main(String[] args) {
 Shape shape1 = new Circle();
 Shape shape2 = new Rectangle(); 
 shape1.draw(); // Calls the draw() method of Circle
 shape2.draw(); // Calls the draw() method of Rectangle
 }
}

In this example in the Java Compiler, objects from subclasses ('Circle' and 'Rectangle') are assigned to a superclass reference ('Shape'), and method calls on these references dynamically invoke the overridden 'draw' method in the corresponding subclass, printing "Drawing a circle" and "Drawing a rectangle" as a result.

Output

Drawing a circle 
Drawing a rectangle

Read More: Polymorphism in Java

Advantages of OOP Concepts in Java

  • Using object-oriented programming in Java enhances the readability and reusability of the code and saves development time
  • Method like Inheritance in OOP concepts eliminates the importance of code redundancy
  • It builds easy communication between objects and classes
  • It gives the highest security by using functions like data abstraction and hiding
  • It is easy to maintain as the modules of OOPs are very flexible

Disadvantages of OOP Concepts in Java

  • Program size in OOPs is much larger than in other methods
  • It requires much knowledge and effort to create a perfect OOPs-based code
  • It executes at a slower time than other methods.

Summary

This article gives a proper idea of what is OOPs in Java and the OOPs principle in Java. So, these were some of the features of OOPs and OOPs concepts in Java that you must know if you wish to pursue a career in Java programming. Of course, there are many other such concepts too, including Java Full Stack Developer, but these are the ones that form the base of this programming language.

FAQs

Encapsulation, inheritance, polymorphism, & abstraction are the four pillars of OOP in Java.

In its complete form, object-oriented programming (OOP) promotes concepts like inheritance, polymorphism, and abstraction for improved code structure and reusability by structuring software into objects that encompass both data and behavior.

The originator of OOP is often referred to as Alan Kay.

In object-oriented programming (OOP), abstraction is the process of decomposing large systems into their basic components while hiding additional information.

In Java, encapsulation is an approach that blocks direct access to an object's internal state and groups data (attributes) and methods (functions) that manipulate the data into a single unit called a class, giving the user control over data access and change.

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingNov 08MON, TUE, WED, THU, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Developer Certification TrainingNov 09SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification TrainingNov 10SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Angular Certification TrainingNov 17SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Software Architecture and Design TrainingNov 24SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 24SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this