THE GENERAL BLOG

Understanding the concept of Encapsulation and Polymorphism in java

Posted on April 12, 2024

Encapsulation is a fundamental principle in object-oriented programming (OOP) where the internal state of an object is hidden from outside access. In Java, encapsulation is achieved using access modifiers. Let's dive into concept of Encapsulation and Polymorphism more deeply with a lots of examples.

What is Encapsulation ?

Encapsulation is a process of binding the class of memeber into a single unit.It protects the data of class to be accessed from outside the class. However it is accessed outside the class by using access modifier let's see how.

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.");
        }
    }

     @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

// Main.java
public class Main {
    public static void main(String[] args) {
        Person person = new Person("shubham", 22);
         System.out.println(person);
        person.setName("pawan");
        person.setAge(29);
        System.out.println(person);

    }
}
Person{name='shubham',age=22}
Person{name='pawan', age=29}

In this example, the Person class encapsulates the data (name and age) and provides public methods to access and modify this data. The data members name and age are declared as private, restricting direct access from outside the class. Instead, access to these fields is controlled through the public getter and setter methods. This encapsulation ensures data integrity by enforcing constraints, such as age cannot be negative.

Polymorphism

The word "poly" means many and "morphs" means forms, So polymorphism means many forms. it is ability of objects to take on multiple forms or to be treated as instances of their parent class.

Types of polymorphism

Types of Polymorphism

Runtime Polymorphism (Method Overriding)

It occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. It allows you to invoke methods on objects of different classes through a reference to their common superclass or interface.

Example:

// Parent class or Base class
class Animal {
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}

// Subclass of Animal
class Cow extends Animal {
    @Override
    public void sound() {
        System.out.println("cow moo");
    }
}

// subclass of Animal
class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("cat meows");
    }
}

// Main.java
public class Main {
    public static void main(String[] args) {
        Animal cow = new Cow(); 
        Animal cat = new Cat(); 
        Animal animal= new Animal();
        Cow cow1= new Cow();
        Cat cat1= new Cat();
        animal.sound();
        cow.sound(); 
        cow1.sound();
        cat.sound(); 
        cat1.sound();
    }
}
output
Animal makes a sound
cow moo
cow moo
cat meows
cat meows

Compile-time Polymorphism (Method Overloading)

It occurs when multiple methods in the same class have the same name but different parameters.When you call an overloaded method, the Java compiler determines the most appropriate method to execute based on the arguments you pass.

Example:

class Example {
   // Method with one integer parameter
   void display(int a) {
       System.out.println("Method with int parameter: " + a);
   }

   // Method with one String parameter
   void display(String b) {
       System.out.println("Method with String parameter: " + b);
   }
     // Method with one double parameter
    void display(double c) {
       System.out.println("Method with double parameter: " + c);
   }
}

public class Main {
   public static void main(String[] args) {
       Example obj = new Example();

       // Calls the method with int parameter
       obj.display(5);

       // Calls the method with String parameter
       obj.display("Hello");
      // Calls the Method with double parameter
       obj.display(5.55);
   }
}
output

Method with int parameter: 5
Method with String parameter: Hello
Method with int parameter: 5.55

Avantages of Polymorphism

  1. Increases code reusability by allowing objects of different classes to be treated as objects of a common class.

  2. Improves readability and maintainability of code by reducing the amount of code that needs to be written and maintained.



The Most Popular Blog

The best tips and tricks on managing digital documents

How to compress or reduce image size online using converteasly ?

Compressing images is crucial for optimizing website performance. Large image file sizes can significantly impact page load times, leading to slower website speeds

Read More >

How to protect your PDF file with password online ?

When sharing sensitive or confidential documents, protecting the PDF ensures that only intended recipients can access the content.

Read More >

How to convert ODF Formula (.odf) file to PDF online using converteasly ?

Educators can convert course materials, lecture notes, and educational resources from ODF to PDF format for distribution to students

Read More >

How to convert PDF to Image online using converteasly?

Simple steps to convert PDF to images online, at no-cost, no-registration, and no-installation needed.

Read More >

How to Escape JSON Using Converteasly.com

Dealing with JSON data often requires ensuring that the text is properly escaped to avoid errors during processing.

Read More >

Simple steps to split single PDF into multiple PDF online using converteasly

you can extract a single chapter from a large book or isolate specific sections for reference or distribution.

Read More >

How to Remove Background of Image using converteasly

In today digital world, having images with transparent backgrounds is often a necessity for designers, content creators, and anyone looking to create polished visuals.

Read More >

Exploring JDK 17 Features: A Comprehensive Guide

Java Development Kit (JDK) 17, released in September 2021, is the Long-Term Support (LTS) version of the Java programming language.

Read More >

How to convert docx file to pdf online free ?

Presentations created in DOCX format might need to be shared with clients or partners. Converting them to

Read More >

How to rotate image left and right online using converteasly ?

Images captured with digital cameras or smartphones may sometimes have incorrect orientations due to device positioning.

Read More >

How to Unescape JSON Using Converteasly.com

Are you dealing with escaped JSON that needs to be converted back to its original form?

Read More >

How to unlock password protected PDF online using converteasly ?

Unlocking password-protected PDFs or removing restrictions can streamline document workflows, especially in business or administrative settings.

Read More >

How to convert Pdf To Docx file online free using converteasly ?

If you have received a document in PDF format but need to continue working on it converting it to DOCX allows you to seamlessly resume

Read More >

How to convert Rich Text Format (.rtf) file to Epub online free using converteasly ?

Educational institutions and educators can convert RTF-based textbooks, study guides, and educational resources into EPUB format

Read More >

Understanding the Concept of Inheritance in Java with application

Let's dive into the concept of inheritance more deeply with a lots of examples

Read More >

How to Convert JPG/PNG to WebP Using Converteasly.com

Optimizing images for the web is essential for faster loading times and better user experience. Converting JPG and PNG images to WebP format is an effective way to achieve this.

Read More >

How to convert PDF to Text free online with no restriction ?

Converting PDF to text makes it easier to search for specific words, phrases, or keywords within the document. Text search functionality allows you to quickly locate relevant information

Read More >

Comprehensive Guide to Exception Handling in Java

Exception handling is a programming practice used to manage errors and exceptional conditions in a controlled manner.

Read More >

How to encode text into base64 format online using converteasly?

In some cases, when passing text data as a parameter in a URL, Base64 encoding can be used to ensure that

Read More >

Free tool to convert Excel (.xls/.xlsx) file to PDF online.

When you want to share your spreadsheet data with others who may not have Excel or who need a format that cannot be easily edited, converting to PDF

Read More >

How to change width and height of image online free ?

Resizing images is crucial for optimizing website performance and improving user experience.

Read More >

Unlocking the Power of Java Multithreading

Multithreading is a programming technique that enables a program to execute multiple threads or flows of execution concurrently

Read More >

Understanding Git and GitHub: A Beginner's Guide with Simple Examples

If you're diving into the world of coding, you've probably heard about Git and GitHub. They're like the dynamic duo of version control, helping developers

Read More >

How to convert png to jpg or jpeg online using converteasly ?

Converting PNG images to JPG format can significantly reduce the file size, making it more suitable for web publishing, email attachments, or

Read More >

Free tool to convert text to pdf online with no restriction

A free tool to convert one or multiple text files to PDF online, at no-cost, no-registration, and no-installation needed.

Read More >

How to convert Rich Text Format (.rtf) file to PDF online using converteasly ?

Legal professionals often convert legal documents, agreements, and contracts from RTF to PDF to maintain document integrity and

Read More >

How to convert image to pdf online using converteasly?

A free tool to convert one or multiple images to PDF online, at no-cost, no-registration, and no-installation needed.

Read More >

How to convert Docx file to Epub online free using converteasly ?

Teachers, educators, and instructional designers can convert lesson plans, textbooks, educational guides, and study materials from DOCX to EPUB

Read More >

How to convert webp to jpg or jpeg or png online using converteasly ?

By converting WebP images to JPEG or PNG, you ensure compatibility with a broader range of devices, applications,

Read More >

Understanding the concept of Encapsulation and Polymorphism in java

Encapsulation is a fundamental principle in object-oriented programming (OOP) where the internal state of an object is hidden from outside access.

Read More >

© 2024 converteasly.com - Made with 💕 for the people of the internet.

Privacy PolicyDisclaimerT&C