Back to Java
2026-02-035 min read

private

Learn private step by step with clear examples and exercises.

Why This Matters

The private access modifier is crucial in Java as it enforces encapsulation, a fundamental principle of object-oriented programming. Encapsulation helps maintain the integrity and security of your data and methods by restricting their access to only the defining class. By mastering the use of private, you'll write more secure, maintainable, and efficient code.

Encapsulation promotes code reusability, reduces complexity, and makes it easier to modify and extend your classes without affecting other parts of the system. It also helps minimize unintended interactions between objects, improving overall program stability.

Prerequisites

To fully understand this tutorial, you should have a solid grasp of:

  1. Basic Java syntax and concepts such as variables, methods, classes, and control structures.
  2. Object-oriented programming principles like encapsulation, inheritance, polymorphism, and interfaces.
  3. Understanding the difference between access modifiers (public, private, protected, and default) in Java.
  4. Familiarity with concepts such as constructors, getter and setter methods, and instance variables.

Core Concept

The private keyword in Java restricts the accessibility of a variable or method to only the defining class. This means that no other class can directly access these private members. Instead, they must be accessed through public methods (getters and setters) provided by the defining class itself.

Example: Private Variables and Methods

public class MyClass {
// Declaring a private variable
private int myPrivateInt;

// A private method to increment the private integer
private void increment() {
myPrivateInt++;
}
}

In this example, myPrivateInt and increment() are both declared as private, which means they can only be accessed within the MyClass itself.

Example: Private Methods with Parameters

public class MyClass {
private void printMessage(String message) {
System.out.println(message);
}
}

In this example, the method printMessage() is declared as private and can only be called from within the same class.

Example: Private Fields with Getters and Setters

public class Person {
// Declaring a private field for name
private String name;

// Creating getter and setter methods for name
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

In this example, the name field is declared as private, and we provide both a getter (to retrieve the value) and a setter (to change the value). This allows other classes to interact with the private data while maintaining encapsulation.

Worked Example

Let's create a Person class with private fields for name and age, public getter methods to access these values, and a constructor that initializes the object with these details:

public class Person {
// Declaring private fields for name and age
private String name;
private int age;

// Creating a constructor to initialize the person's name and age
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getter for the name
public String getName() {
return name;
}

// Getter for the age
public int getAge() {
return age;
}
}

Now, we can create a Main class to test our Person class:

public class Main {
public static void main(String[] args) {
Person john = new Person("John", 30);
System.out.println("Name: " + john.getName());
System.out.println("Age: " + john.getAge());
}
}

Common Mistakes

  1. Trying to access private members directly from another class: Private members can only be accessed through public methods in the defining class.
  2. Not providing getter and setter methods for private fields: It's essential to provide these methods to allow other classes to interact with your private data while maintaining encapsulation.
  3. Overusing the private keyword: While encapsulation is important, excessive use of private can make your code difficult to test and maintain.
  4. Forgetting to initialize private fields in the constructor: Private fields must be initialized before they can be used within the class.
  5. Misusing final with private members: When a private member is declared as final, it cannot be changed, even within the defining class. Be mindful of when to use final and when to use private.
  6. Not validating input to setter methods: It's crucial to validate user input before setting values for private fields to prevent unexpected behavior or errors.
  7. Not following a consistent naming convention for getters and setters: Stick to a standard naming convention (e.g., getXxx() and setXxx(...)) to make your code more readable and maintainable.

Practice Questions

  1. Create a Rectangle class with private fields for width and height, public getter methods to access these values, and a constructor that initializes the object with these details.
  2. Write a Car class with private fields for the car's brand, model, year, and color, and public getter methods to access these values. Include a constructor that initializes the object with these details.
  3. Modify the Person class from the Worked Example to include setter methods for the name and age.
  4. Create a Square class that extends the Rectangle class, overriding its methods to ensure that width and height are always equal (i.e., a square has four equal sides).
  5. Write a Circle class with private fields for the radius, and public getter and setter methods to access these values. Include a method to calculate the circle's area using the formula π * r^2.
  6. Implement a Validator class that validates user input before setting values for private fields in other classes (e.g., checking if an age is greater than zero, or if a name is not empty).

FAQ

  1. Why use private fields instead of public ones? Private fields help encapsulate your data, ensuring its integrity and making it harder for external code to accidentally modify or misuse it.
  2. How do I access private members from another class? You can't directly access private members from another class. Instead, you should use the public getter methods provided by the defining class.
  3. When should I use private fields and when should I use public ones? Use private fields for sensitive data that should be protected, and public fields for data that doesn't require such protection or is intended to be easily accessible.
  4. What is the difference between private and final in Java? Private restricts access to a member within the defining class, while final makes a member constant (i.e., its value cannot be changed).
  5. Can I make a method private in an interface? No, methods cannot be declared as private in interfaces since they are meant to define a contract for implementation by other classes.
  6. What is the purpose of encapsulation and why is it important? Encapsulation helps maintain the integrity and security of your data and methods by restricting their access to only the defining class, promoting code reusability, reducing complexity, and improving overall program stability.
private | Java | XQA Learn