Data hiding helps keep important information safe inside a class. It stops other parts of the program from changing data by mistake.
Data hiding in Java
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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; } }
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()); } }
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.
Practice
1. What is the main purpose of
data hiding in Java?easy
Solution
Step 1: Understand data hiding concept
Data hiding means keeping variables private inside a class to prevent direct access from outside.Step 2: Identify the purpose
This protects data from unwanted changes and bugs by controlling access through methods.Final Answer:
To keep class variables private and protect them from outside access -> Option AQuick Check:
Data hiding = keeping variables private [OK]
Hint: Data hiding means making variables private [OK]
Common Mistakes:
- Thinking data hiding means encrypting data
- Confusing data hiding with making variables public
- Believing data hiding hides methods from UI
2. Which of the following is the correct way to declare a private variable in a Java class?
easy
Solution
Step 1: Recall Java access modifiers
Private variables are declared with the keywordprivateto restrict access.Step 2: Identify correct syntax
Onlyprivate int age;correctly declares a private variable.Final Answer:
private int age; -> Option DQuick Check:
Private variable = private keyword [OK]
Hint: Use 'private' keyword to hide variables [OK]
Common Mistakes:
- Using public or protected instead of private
- Omitting access modifier defaults to package-private
- Confusing private with protected
3. What will be the output of the following Java code?
class Person {
private String name = "Alice";
public String getName() {
return name;
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.getName());
}
}medium
Solution
Step 1: Understand private variable access
The variablenameis private but accessed via the public gettergetName().Step 2: Trace the output
The getter returns "Alice", soSystem.out.printlnprints "Alice".Final Answer:
Alice -> Option CQuick Check:
Getter returns private value = Alice [OK]
Hint: Private data accessed via public getter returns value [OK]
Common Mistakes:
- Expecting direct access to private variable
- Thinking code causes compilation error
- Confusing output with null or error
4. Identify the error in this code related to data hiding:
class BankAccount {
private double balance;
public void setBalance(double balance) {
balance = balance;
}
public double getBalance() {
return balance;
}
}medium
Solution
Step 1: Analyze setter method
The setter usesbalance = balance;which assigns the parameter to itself, not the class variable.Step 2: Identify correct assignment
It should usethis.balance = balance;to update the private variable.Final Answer:
The setter method does not update the private variable -> Option AQuick Check:
Setter must update class variable using 'this' [OK]
Hint: Use 'this' to assign parameter to class variable [OK]
Common Mistakes:
- Forgetting 'this' keyword in setter
- Making getter private by mistake
- Changing variable access to public unnecessarily
5. You want to protect a class's sensitive data but allow controlled updates only if the new value is positive. How would you implement this using data hiding in Java?
hard
Solution
Step 1: Use private variable for data hiding
Keep the sensitive variable private to prevent direct external access.Step 2: Implement setter with condition
Write a setter method that updates the variable only if the new value is positive, ensuring controlled updates.Final Answer:
Make the variable private and write a setter that updates only if the value is positive -> Option BQuick Check:
Private variable + conditional setter = safe updates [OK]
Hint: Use private variable with conditional setter method [OK]
Common Mistakes:
- Making variable public and trusting external checks
- Using protected instead of private for sensitive data
- Not validating data in setter method
