java

Java Encapsulation


What is Encapsulation?

Encapsulation is one of the core fundamental concept of Object-Oriented Programming (OOP) principles which contain data (attributes) and methods (functions) that binds data into a single unit, known as a class.

 

Syntax

public class ClassName {
    // Private variables (attributes)
    private dataType variable1;
    private dataType variable2;

    // Constructor
    public ClassName(type var1, type var2, ...) {
        // Initialize the private variables in the constructor
        variable1 = var1;
        variable2 = var2;

    }

    // Public methods
    public dataType fun() {
        // code;
    }

    // Public methods
    public void method() {
        // Perform any necessary logic here
    }

	// ...you may define other getter and setter methods for other variables
}

 

Example

public class AddTwoNumbers {

    private int num1;
    private int num2;

    // Constructor
    public AddTwoNumbers(int a, int b) {
        num1 = a;
        num2 = b;
    }

    // Method to add two numbers
    public int addNumbers() {
        int sum = num1 + num2;
        return sum;
    }

    public static void main(String[] args) {
        // Creating an object of the class
        AddTwoNumbers obj = new AddTwoNumbers(5, 7);

        // Calling the addNumbers method
        int result = obj.addNumbers();

        // Displaying the result
        System.out.println("Sum of two numbers: " + result);
    }
}