Example: There is a DButils tool class, which is specially used to add, delete, change and check the database.
public class DButils {
public void add() {
System.out.println("对数据库进行add操作");
}
public void update() {
System.out.println("对数据库进行update操作");
}
public void query() {
System.out.println("对数据库进行query操作");
}
public void delete() {
System.out.println("对数据库进行delete操作");
}
}
Now, call the methods in DButils in the Service class,
public class Service {
private DButils utils = new DButils();
public void methodA() {
utils.add();
utils.query();
}
public void methodB() {
utils.update();
utils.add();
}
public void methodC() {
utils.delete();
utils.add();
}
}
It can be seen that only one DButils object is created in the Service class, but it can be called multiple times in the methodA, methodB, methodC methods below.
Benefits :
1. Call the methods in DButils multiple times, but只需要创建一次对象
, therefore, greatly save the memory space required to create the object, and easy to call [often used in development]
2. private means private, visible in the same class, so The object cannot be directly modified in other classes, ensuring the security of the object.