Modifiers & Encapsulation - [Java OOP #3]
Tags: java, oop, computerscience, beginners
Published: 2022-09-26 08:03:17

In Java, there are two types of modifiers: **access modifiers** and **non-access modifiers**.

## Access Modifiers
Access modifiers are used to specify the scope of classes, constructors, methods, variables, etc. There are 4 types of access modifiers in Java:

|Access Modifier|Description|
|---------------|-----------|
|default|accessible within the same package|
|`public`|accessible for all classes|
|`private`|accessible within the declared class|
|`protected`|accessible within the package or all subclasses|

**Examples:**
+ default

```java
package p1;

// class Example is accessible within package p1
class Example {
    void display() {
        System.out.println("Hello");
    }
}
```

+ public

```java
// class A can be accessed anywhere
public class A {
    // display method can be accessed anywhere
    public void display() {
        System.out.println("Hello");
    }
}
```

```java
class B {
    public static void main(String args[]) {
        // creating object of public class A
        A obj = new A();

        // calling public display() method
        obj.display();
    }
}
```

+ private

```java
class A { 
    // variable x can only be accessed in class A
    private int x = 1;  

    // display() method can only be accessed in class A
    private void display() {
        System.out.println("Hello");
    }
}  
    
public class Example {  
    public static void main(String args[]){  
        // object can be created as class A has default access
        A obj=new A();  
        System.out.println(obj.x); // compile time error  
        obj.display(); // compile time error  
    }  
}  
```

+ protected

```java
package p1;  

public class A{  
    /* display() can be accessed by package p1 
    / or subclasses of A in another package */
    protected void display(){
        System.out.println("Hello");
    }  
}  
```

```java
// class B is a subclass of A
class B extends A{  
    public static void main(String args[]){  
        B obj = new B();  
        obj.display();  
    }  
}  

```

---

## Non-access Modifiers
Non-access modifiers specifies the characteristics of classes, methods, variables, etc. Some commonly used non-access modifiers are: 


|Non-access Modifier|Description|
|---------------|-----------|
|`final`|final classes cannot be inherited <br>final methods cannot be overriden<br>final variables can only be initialised once|
|`static`|Static methods or fields are a part of the class and not an object. They can be called without creating an object of the class.|

**Examples:**
+ final

```java
public class Example {
    final double PI = 3.14;

    public static void main(String[] args) {
        Example obj = new Example();
        obj.PI = 3; // compile time error
    }
}
```

+ static 
```java
public class Example {
    static void myStaticMethod() {
        System.out.println("Static methods can be called without creating objects");
    }

    public static void main(String[] args) {
        myStaticMethod(); // calling the static method
    }
}
```

---
 
## Encapsulation
Encapsulation is defined as the wrapping up of data under a single unit. Encapsulation allows **data hiding**, which is useful when we do not want the user to have have direct access to data in the class.

To achieve encapsulation, declare variables as private and provide public setter and getter methods to modify the variables.


![Encapsulation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xc71pcxr2egcooi8zh0g.png)

**Example:**
```java
public class Person {
    private String name; 
 
    public String getName() {
      return name;
    }

    public void setName(String newName) {
      this.name = newName;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person();
        person1.setName("Bob"); // initialise name using setter
        person1.name = "John";  // error as name is private
    }
}

```