简体   繁体   English

java中两个不同类之间的调用参数

[英]call parameters between two different classes in java

I have two classes(in different file) and one main class.我有两个类(在不同的文件中)和一个主类。 I want to use their methods and parameters (such as int) in other method but when I create each of them as new I faced "java.lang.StackOverflowError".我想在其他方法中使用它们的方法和参数(例如 int),但是当我将它们中的每一个都创建为新的时,我遇到了"java.lang.StackOverflowError".

my purpose : Main >create class1>go to class1 and send int to class2>do sth and return result as int to class1 again and print the result.我的目的: Main >create class1> go to class1 and send int to class2> do sth and return result as int to class1 again and print the result.

public class Class1 {

    Class2 class2=new Class2();
    protected int b=4;
    public void start (int c)
    {
        class2.run(b);
        System.out.println("Numbber :"+c);
    }
}



public class Class2 {

    Class1 class1 = new Class1();
    protected int a=5;

    public void run(int b) {
        int c=b+10+a;
        class1.start(c);

    }
}


public class Main {

    public static void main(String[] args) {
        Class1 class1 = new Class1();
        class1.start(1);
        //enter code here

    }
}

从 Class2 run的方法和从 Class1 start的方法之间有循环引用。

Your run method calls start , which calls run , which calls start , which calls...你的run方法调用start ,它调用run ,它调用start ,它调用...

my purpose : Main >create class1>go to class1 and send int to class2>do sth and return result as int to class1 again and print the result.我的目的: Main >create class1> go to class1 and send int to class2> do sth and return result as int to class1 again and print the result.

If this is your purpose just make a method to do what you want and then return the result:如果这是您的目的,只需创建一个方法来执行您想要的操作,然后返回结果:

public int foo(int b) {
    return b+10+a;
}

So that your start method will call foo() and do the necessary calculations and then return the results instead of calling the method again.这样您的start方法将调用foo()并进行必要的计算,然后return结果而不是再次调用该方法。 However Java is pass by value, so you will have to resolve the results of foo() to your variable.但是 Java 是按值传递的,因此您必须将foo()的结果解析为您的变量。 However you can simply just print the results:但是,您可以简单地打印结果:

public void start (int c)
{        
    System.out.println("Number :"+ class2.foo(b));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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