Skip to content

Latest commit

 

History

History
116 lines (87 loc) · 4.17 KB

Encapsulation.md

File metadata and controls

116 lines (87 loc) · 4.17 KB

Encapsulation

( aim to restrict direct access )

Binding code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.

Encapsulation

  • Binding of data and corresponding methods into a single unit is called "Encapsulation".
  • If any java class follows data hiding and abstraction then such class is referred as "Encapsulation class"

Encapsulation = Data Hiding + Data Abstraction


class Person {
    private String name; // Instance Variable
    private int age; // Instance Variable

    public String getName() {
        return name; // Getters for Name
    }

    public void setName(String name) {
        this.name = name; // Setters for Name
    }

    public int getAge() {
        return age; // Getters for Age
    }

    public void setAge(int age) {
        this.age = age; // Setters for Age
    }
}

public class demo {
    public static void main(String[] args) {
        Person person = new Person(); // creating object person
        person.setName("Rohit");
        person.setAge(22);

        System.out.println("Name:" + person.getName());
        System.out.println("Age:" + person.getAge());
    }
}

Shadowing Problem:

  • If both local variable and instance variable have the same name inside the method then it would result in a name_class and jvm will always give preference for local variable. This approach is called the "Shadowing Problem".

Getters

Getters method are used to get the value from the instance variable of the class.

Syntax for getters method

  • the method name should start with get
  • it should be public
  • return type should not be void
  • it should not have any arguments
public String getName() {
        return name; // Getters for Name
    }

Setters

Setters method are used to set the value to the instance variables of the class.

Syntax for setters method

  • the method name should start with set
  • it should be public
  • return type should be void
  • it should have some arguments
public void setName(String name) {
        this.name = name; // Setters for Name
    }

Interview Question

1. What is Encapsulation in Java? Why is it called Data hiding?

Ans:
`Encapsulation` refers to the bundling of fields and methods inside a single class. `Data Hiding`

More Topics


Feel Free to connect