What is polymorphism and Encapsulation in Oject oriented programming ?

In oop(object oriented programming) what is polymorphism and Encapsulation can anyone tell me of that answer .

1 Answer

Polymorphism (Meaning: Many Forms)

Definition:

The capacity of a single function, method, or object to assume various forms is known as polymorphism. Depending on the object or data being worked with, it permits the same interface or method name to act differently.

    class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("Cat meows");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a;
        a = new Dog(); // Polymorphism at work
        a.sound();     // Output: Dog barks

        a = new Cat();
        a.sound();     // Output: Cat meows
    }
} 
      
    

Encapsulation (Meaning: Wrapping Up Data)

Definition:

Encapsulation is the process of just revealing what is required while concealing an object's internal workings. It entails limiting direct access to some of the object's components and putting code (methods) and data (variables) together in a class.

How it works: Variables are declared private. Access to them is provided through public getter and setter methods.

   class Student {
    private String name; // Private variable

    // Getter method
    public String getName() {
        return name;
    }

    // Setter method
    public void setName(String newName) {
        name = newName;
    }
}

public class TestEncapsulation {
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("Alice");
        System.out.println("Student name: " + s.getName());
    }
}                                  

We use cookies to enhance your experience, to provide social media features and to analyse our traffic. By continuing to browse, you agree to our Privacy Policy.