0
0
Javaprogramming~5 mins

Data hiding in Java

Choose your learning style9 modes available
Introduction

Data hiding helps keep important information safe inside a class. It stops other parts of the program from changing data by mistake.

When you want to protect sensitive information like passwords or personal details.
When you want to control how data is changed or accessed in your program.
When you want to make your code easier to fix and improve later.
When you want to prevent bugs caused by unexpected changes to data.
Syntax
Java
class ClassName {
    private DataType variableName;

    public DataType getVariableName() {
        return variableName;
    }

    public void setVariableName(DataType value) {
        variableName = value;
    }
}

private means only the class itself can access the variable.

Use getters and setters to read and change the variable safely.

Examples
This example hides the name variable and uses methods to access it.
Java
class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String newName) {
        name = newName;
    }
}
This example hides the balance and controls how money is added or taken out.
Java
class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
}
Sample Program

This program hides the age of a student. It only allows positive ages to be set. It shows how data hiding protects the data.

Java
class Student {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int newAge) {
        if (newAge > 0) {
            age = newAge;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.setAge(20);
        System.out.println("Student age: " + s.getAge());

        s.setAge(-5); // invalid age, should not change
        System.out.println("Student age after invalid update: " + s.getAge());
    }
}
OutputSuccess
Important Notes

Always use private for variables you want to hide.

Use getters and setters to control access and validation.

Data hiding helps keep your program safe and easier to maintain.

Summary

Data hiding means keeping variables private inside a class.

Use getters and setters to safely access and change data.

This protects data from unwanted changes and bugs.