Home Java javaTutorial What is encapsulation and how to use it.

What is encapsulation and how to use it.

Sep 08, 2024 pm 04:30 PM

What is encapsulation and how to use it.

What is encapsulation?
Encapsulation in Java is all about keeping the details of how something works hidden while still letting others use it. You group your data (like variables) and methods (like functions) into one unit, called a class. Instead of letting everyone directly access your data, you provide methods (getters and setters) to control how it’s accessed or changed. This way, you protect your data and keep your code clean and organized, without letting anyone mess with the inner workings unless you want them to.

How to use it
To use encapsulation in Java, you create a class with private fields and provide public methods (like getters and setters) to access and modify those fields. This ensures that the data can only be changed in a controlled way. For example, if you want to create a Person class where the name and age are private, you would use getters to retrieve the values and setters to update them. Here's how you can do it:

public class Person {
    // Private fields
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

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

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

    // Setter for age
    public void setAge(int age) {
        if(age > 0) { // Simple validation
            this.age = age;
        } else {
            System.out.println("Age must be positive.");
        }
    }
}

// Using the Person class
public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 25);

        // Accessing fields using getters
        System.out.println(person.getName()); // Output: John
        System.out.println(person.getAge());  // Output: 25

        // Modifying fields using setters
        person.setName("Jane");
        person.setAge(30);

        System.out.println(person.getName()); // Output: Jane
        System.out.println(person.getAge());  // Output: 30
    }
}

Copy after login

Lets break it down
Let's break down the code and explain each section step by step:

1. Class Definition with Private Fields
public class Person {
    // Private fields
    private String name;
    private int age;
}

Copy after login
Explanation:

This is the Person class where we define two private fields: name (a String) and age (an int). By making these fields private, we ensure that no other class can directly access or modify them. This is the core idea of encapsulation — hiding the internal state of an object.

2. Constructor
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

Copy after login
Explanation:

The constructor initializes the Person object when it's created. It takes two parameters, name and age, and assigns these values to the private fields. This ensures that when a new Person object is created, it starts with valid data.

3. Getter and Setter for
    // Getter for name
    public String getName() {
        return name;
    }

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

Copy after login
Explanation:

The constructor initializes the Person object when it's created. It takes two parameters, name and age, and assigns these values to the private fields. This ensures that when a new Person object is created, it starts with valid data.

4. Getter and Setter for age (with validation)
    // Getter for age
    public int getAge() {
        return age;
    }

    // Setter for age
    public void setAge(int age) {
        if (age > 0) { // Simple validation
            this.age = age;
        } else {
            System.out.println("Age must be positive.");
        }
    }

Copy after login
Explanation:

The getter getAge() works the same way as the one for name, allowing access to the age field.
The setter setAge() not only allows modification of the age field but also adds a validation check. The if condition ensures that the age is only set if it's a positive number. If an invalid age is provided (like a negative number), the setter prevents the update and prints a message instead. This is an example of how encapsulation lets you control what kind of data can be set.

5. Using the Person Class
// Using the Person class
public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 25);

        // Accessing fields using getters
        System.out.println(person.getName()); // Output: John
        System.out.println(person.getAge());  // Output: 25

        // Modifying fields using setters
        person.setName("Jane");
        person.setAge(30);

        System.out.println(person.getName()); // Output: Jane
        System.out.println(person.getAge());  // Output: 30
    }
}

Copy after login
Explanation:

In this section, we create a Person object (person) using the constructor. The constructor sets the initial name as "John" and age as 25.

Then, we use the getters (getName() and getAge()) to print the values of name and age. After that, we use the setters (setName() and setAge()) to update the values. Finally, the updated values are printed using the getters again.

Key Points of Encapsulation in Action:

  • Data Protection:

    The private fields can't be directly accessed or modified from outside the class.

  • Controlled Access:

    Getters and setters provide a controlled way of accessing and modifying the private fields.

  • Validation:

    The setter for age demonstrates how you can enforce rules (e.g., age must be positive) to protect the data from invalid input.

The above is the detailed content of What is encapsulation and how to use it.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles