Home > Java > Javagetting Started > body text

What does java encapsulation mean?

王林
Release: 2020-08-12 16:19:03
Original
2889 people have browsed it

What does java encapsulation mean?

Encapsulation refers to a method of packaging and hiding the implementation details of an abstract functional interface.

(Recommended tutorial: java introductory tutorial)

The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code .

Advantages:

  • Good encapsulation can reduce coupling.

  • The structure inside the class can be modified freely.

  • Can provide more precise control over member variables.

  • Hide information and implement details.

(Learning video recommendation: java course)

Encapsulation steps

1. Modify the visibility of attributes to limit Access to attributes (generally restricted to private), for example:

public class Person {
    private String name;    
    private int age;
}
Copy after login

In this code, the name and age attributes are set to private, which can only be accessed by this class, and no other class can access it. This way Information is hidden.

2. Provide external public method access to each value attribute, that is, create a pair of assignment methods for access to private attributes, for example:

public class Person{
    private String name;    
    private int age;    
    public int getAge(){
        return age;    
    }

    public String getName(){
        return name;    
    }

    public void setAge(int age){
        this.age = age;    
    }

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

Use this key The word is to resolve the conflict of the same name between the instance variable (private String name) and the local variable (name variable in setName(String name)).

The above is the detailed content of What does java encapsulation mean?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!