简体   繁体   中英

How to use same object at different places in a class?

I have written small java code, and want to use same object which I have created in main method in other methods as well in a class. Is there any way ? I dont want to create every time new object in Checklength method just to call digitSum. I want use same o object created in main method.

Note: Without changing method properties

public class UserMainCode {

    public int digitSum(int input1) {
        int num = input1;
        int sum = 0;
        int output = 0;
        int length = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        output = sum;
        length = Integer.valueOf(Integer.toString(output).length());
        Checklength(length, output);
        return length;
    }

    public static void Checklength(int length, int sum) {
        if (length > 1) {
            UserMainCode b = new UserMainCode();
            b.digitSum(sum);
        }
        else {
            System.out.println(sum);
        }
    }

    public static void main(String[] args) {
        UserMainCode o = new UserMainCode();
        o.digitSum(976592);
    }
}

Any ideas ?

The thing to do in this situation is to remove static from the checklength method. static means that the method belongs at the class-level rather than the instance level. If you remove that, checklength will be back on the instance-level and will be able to call digitSum on the same instance (which can be explicitly accessed via the keyword this ).

public class UserMainCode {

    public int digitSum(int input1) {
        int num = input1;
        int sum = 0;
        int output = 0;
        int length = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        output = sum;
        length = Integer.valueOf(Integer.toString(output).length());
        Checklength(length, output);
        return length;
    }

    public void checklength(int length, int sum) {
        if (length > 1) {
            // deleted instance b - we don't need it
            digitSum(sum);  // implicitly means  this.digitSum(sum); 
        }
        else {
            System.out.println(sum);
        }
    }
}

All of these operations now happen on the instance created in your main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM