Before the java class, use the function of private static class name object = new class name ().

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.

Published 21 original articles · won 29 · views 2821

Guess you like

Origin blog.csdn.net/VariatioZbw/article/details/105475292