Tools Tags
directory
Tools Tags
Java encapsulation
In object-oriented programming methods, encapsulation (English: Encapsulation) refers to a method of partially packaging and hiding the implementation details of an abstract functional interface.
Encapsulation can be thought of as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by the external class.
To access the code and data of this class, you must pass strict interface control.
The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code.
Proper encapsulation can make the program code easier to understand and maintain, and also enhance the security of the program code.
Example
Let us look at an example of a java encapsulation class:
/* 文件名: EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}The public method in the above example is the entrance for external classes to access member variables of this class.
Normally, these methods are called getter and setter methods.
Therefore, any class that wants to access private member variables in the class must go through these getter and setter methods.
The following example illustrates how the variables of the EncapTest class are accessed:
/* F文件名 : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}The above code is compiled and run and the results are as follows:
Name : James Age : 20
Hot AI Tools
Undress images for free
Online AI tool for removing clothes from photos.
AI-powered app for creating realistic nude photos
AI image generator for creative art from text prompts.
AI powered investment research for smarter decisions
Hot Article
Hot Topics
20536
7
13640
4
Popular tool
Easy-to-use and free code editor
Chinese version, very easy to use
Powerful PHP integrated development environment
Visual web development tools
God-level code editing software (SublimeText3)












![Getting Started with PHP Practical Development: PHP Quick Creation [Small Business Forum]](https://img.php.cn/upload/course/000/000/035/5d27fb58823dc974.jpg)