Information Hiding
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 12 of 87.
Information hiding is the principle of restricting direct access to an object's internal data. By combining private fields with getters and setters, you create a protective barrier around your object's state.
Consider what happens without information hiding:
public class Temperature {
public double celsius; // Exposed directly
}
// Anyone can set invalid values
Temperature t = new Temperature();
t.celsius = -500; // Below absolute zero - impossible!With information hiding, you control how data is accessed and modified:
public class Temperature {
private double celsius;
public void setCelsius(double celsius) {
if (celsius >= -273.15) {
this.celsius = celsius;
}
}
public double getCelsius() {
return celsius;
}
}Now invalid temperatures are rejected automatically. The internal representation is hidden - you could later change how temperature is stored internally (perhaps to Kelvin) without affecting code that uses the class.
This approach offers three key benefits: validation ensures data integrity, flexibility allows internal changes without breaking external code, and control lets you decide exactly what operations are permitted on your data.
Challenge
EasyLet's build a Password management class that demonstrates information hiding by protecting sensitive data and enforcing security rules through controlled access.
You'll create two files to organize your code:
Password.java: Create a Password class that hides its internal data and controls how passwords can be set and accessed:- A private
passwordfield (String) that stores the actual password - A private
minLengthfield (int) that defines the minimum acceptable password length - A constructor that takes the minimum length requirement
- A setter
setPassword(String password)that only accepts passwords meeting the minimum length requirement. If valid, store it and returntrue; if too short, don't change the password and returnfalse - A getter
getMaskedPassword()that returns the password with all characters replaced by asterisks (*) - never expose the actual password! - A method
checkPassword(String attempt)that returnstrueif the attempt matches the stored password,falseotherwise - A getter
getLength()that returns the length of the current password (or 0 if no password is set)
- A private
Main.java: Create a Password object with a minimum length of 6, then read two inputs: a password to set and an attempt to check. Print three lines:Set: trueorSet: false(result of setting the password)Masked: ******(the masked version of the password)Match: trueorMatch: false(result of checking the attempt)
You will receive two inputs: the password to set, and the password attempt to check.
Notice how the actual password is never directly accessible from outside the class - this is information hiding in action. The class controls exactly what information is revealed and how the password can be modified.
Cheat sheet
Information hiding restricts direct access to an object's internal data by using private fields combined with getters and setters.
Without information hiding, fields are exposed and can be set to invalid values:
public class Temperature {
public double celsius; // Exposed directly
}
Temperature t = new Temperature();
t.celsius = -500; // Invalid value allowedWith information hiding, you control access and validate data:
public class Temperature {
private double celsius;
public void setCelsius(double celsius) {
if (celsius >= -273.15) {
this.celsius = celsius;
}
}
public double getCelsius() {
return celsius;
}
}Key benefits of information hiding:
- Validation: Ensures data integrity by rejecting invalid values
- Flexibility: Allows internal changes without affecting external code
- Control: Lets you decide what operations are permitted on your data
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the password to set
String passwordToSet = scanner.nextLine();
// Read the password attempt to check
String passwordAttempt = scanner.nextLine();
// TODO: Create a Password object with minimum length of 6
// TODO: Set the password and print the result ("Set: true" or "Set: false")
// TODO: Print the masked password ("Masked: ******")
// TODO: Check the password attempt and print the result ("Match: true" or "Match: false")
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System