Introduction
Private methods are methods that can only be accessed within the same class. They are used for internal implementation and helper operations.
Syntax
class ClassName {
private returnType methodName() {
// method body
}
}
Basic Example
class Calculator {
// Private method - only accessible within this class
private int square(int num) {
return num * num;
}
// Public method - can call private method
public void displaySquare(int num) {
int result = square(num); // Call private method
System.out.println("Square: " + result);
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.displaySquare(5); // ✓ OK: public method
// calc.square(5); // ❌ Error: square() is private
}
}
Why Use Private Methods?
1. Encapsulation:
Hide internal implementation details.
2. Code Reusability:
Reuse code within the class without exposing it.
3. Security:
Prevent unauthorized access to sensitive operations.
4. Maintainability:
Change internal logic without affecting external code.
Complete Example
class BankAccount {
private double balance;
// Private method for validation
private boolean isValidAmount(double amount) {
return amount > 0;
}
// Private method for updating balance
private void updateBalance(double amount) {
balance += amount;
}
// Private method for logging
private void log(String message) {
System.out.println("[LOG] " + message);
}
// Public method uses private methods
public void deposit(double amount) {
if (isValidAmount(amount)) {
updateBalance(amount);
log("Deposited: " + amount);
} else {
System.out.println("Invalid amount");
}
}
public void withdraw(double amount) {
if (isValidAmount(amount) && balance >= amount) {
updateBalance(-amount);
log("Withdrawn: " + amount);
} else {
System.out.println("Cannot withdraw");
}
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
System.out.println("Balance: " + account.getBalance());
// Cannot call private methods
// account.isValidAmount(100); // ❌ Error
// account.updateBalance(100); // ❌ Error
// account.log("Test"); // ❌ Error
}
}
Helper Methods
Private methods often serve as helper methods for public methods.
class Student {
private String name;
private int[] marks;
public Student(String name, int[] marks) {
this.name = name;
this.marks = marks;
}
// Private helper method
private int calculateTotal() {
int total = 0;
for (int mark : marks) {
total += mark;
}
return total;
}
// Private helper method
private double calculateAverage() {
return (double) calculateTotal() / marks.length;
}
// Public methods use private helpers
public void displayResult() {
int total = calculateTotal();
double average = calculateAverage();
System.out.println("Name: " + name);
System.out.println("Total: " + total);
System.out.println("Average: " + average);
if (average >= 50) {
System.out.println("Status: Pass");
} else {
System.out.println("Status: Fail");
}
}
}
public class Main {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92, 88};
Student s = new Student("John", marks);
s.displayResult(); // ✓ OK: public method
// Cannot access private methods
// s.calculateTotal(); // ❌ Error
// s.calculateAverage(); // ❌ Error
}
}
Validation with Private Methods
class Employee {
private String name;
private int age;
private double salary;
// Private validation methods
private boolean isValidName(String name) {
return name != null && !name.trim().isEmpty();
}
private boolean isValidAge(int age) {
return age >= 18 && age <= 65;
}
private boolean isValidSalary(double salary) {
return salary > 0;
}
// Public setter using private validation
public void setName(String name) {
if (isValidName(name)) {
this.name = name;
} else {
System.out.println("Invalid name");
}
}
public void setAge(int age) {
if (isValidAge(age)) {
this.age = age;
} else {
System.out.println("Invalid age");
}
}
public void setSalary(double salary) {
if (isValidSalary(salary)) {
this.salary = salary;
} else {
System.out.println("Invalid salary");
}
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Private vs Public Methods
| Private Methods | Public Methods |
|---|---|
| Only within class | Accessible everywhere |
| Internal implementation | External interface |
| Helper methods | Main functionality |
| Can be changed freely | Affects external code |
| Not inherited | Inherited by subclasses |
Example: Complex Calculation
class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// Private helper methods
private double square(double n) {
return n * n;
}
private double getPI() {
return 3.14159;
}
// Public methods use private helpers
public double getArea() {
return getPI() * square(radius);
}
public double getCircumference() {
return 2 * getPI() * radius;
}
public void displayInfo() {
System.out.println("Radius: " + radius);
System.out.println("Area: " + getArea());
System.out.println("Circumference: " + getCircumference());
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5);
circle.displayInfo();
// Cannot access private methods
// circle.square(5); // ❌ Error
// circle.getPI(); // ❌ Error
}
}
Benefits
- Data Hiding: Internal logic hidden
- Flexibility: Change private methods without affecting public interface
- Code Organization: Break complex logic into smaller methods
- Security: Prevent misuse of internal methods
- Testing: Can change implementation without breaking tests
When to Use Private Methods
Use private methods for:
- Helper/utility functions
- Validation logic
- Internal calculations
- Code reuse within class
- Breaking down complex public methods
Use public methods for:
- External interface
- Main functionality
- Methods called by other classes
Quick Reference
class Example {
private int value;
// Private method
private boolean validate(int v) {
return v > 0;
}
// Public method calling private
public void setValue(int v) {
if (validate(v)) { // Call private
value = v;
}
}
}
// Usage
Example obj = new Example();
obj.setValue(10); // ✓ OK
// obj.validate(10); // ❌ Error: private
Exam Tips
Remember:
- private methods = same class only
- Cannot access from outside class
- Used for helper functions
- Provide encapsulation
- Can call from public methods
- Not inherited by subclasses
- Can change without affecting external code
- Used for internal implementation
Common Questions:
- What are private methods?
- Why use private methods?
- Can private methods be called outside class?
- Difference between private and public methods?
- Benefits of private methods?
- When to use private methods?