Java同时调用类

Jat*_*gra 1 java stack-overflow

有两个java类都具有main函数.现在我必须首先将第一类对象调用到第二类对象和第二类对象.每当我这样做它就会给出堆栈溢出异常.有没有办法同时称呼这些?

头等舱:

 public class ChangePasswordLogin extends javax.swing.JFrame { 
     Connection con = null; 
     Statement stmt = null; 
     ResultSet rs = null; 
     String message = null; 
     RandomStringGenerator rsg = new RandomStringGenerator(); 
     MD5Generator pass = new MD5Generator(); 
     PopUp popobj = new PopUp();
     ForgotPassword fpemail = new ForgotPassword();
Run Code Online (Sandbox Code Playgroud)

二等:

public class ForgotPassword extends javax.swing.JFrame { 
    Connection con = null; 
    Statement stmt = null;
    ResultSet rs = null;
    String message = null; 
    String useremail; 
    PopUp popobj = new PopUp(); 
    RandomStringGenerator rsg = new RandomStringGenerator(); 
    MD5Generator pass = new MD5Generator(); 
    ChangePasswordLogin cpl = new ChangePasswordLogin();
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

你已经进行了递归,其中类A在其构造函数中创建了类B的实例,而类B在其构造函数或启动代码中创建了A的实例.这将一直持续到你内存不足为止.解决方案不是这样做的.使用setter方法在构造函数和启动代码之外设置实例.

这可以简单地用以下方式证明:

// this will cause a StackOverfowException
public class RecursionEg {
   public static void main(String[] args) {
      A a = new A();
   }
}

class A {
   private B b = new B();
}

class B {
   private A a = new A();
}
Run Code Online (Sandbox Code Playgroud)

用setter方法解决:

// this won't cause a StackOverfowException
public class RecursionEg {
   public static void main(String[] args) {
      A a = new A();
      B b = new B();
      a.setB(b);
      b.setA(a);
   }
}

class A {
   private B b;

   public void setB(B b) {
      this.b = b;
   }
}

class B {
   private A a;

   public void setA(A a) {
      this.a = a;
   }
}
Run Code Online (Sandbox Code Playgroud)

替换A和B的ForgotPassword和ChangePasswordLoging.

或者你可以像下面的代码一样,在那里你要注意创建每种类型的一个实例:

public class RecursionEg {
   public static void main(String[] args) {
      A a = new A();
   }
}

class A {
   private B b = new B(this);   
}

class B {
   private A a;

   public B(A a) {
      this.a = a;
   }

   public void setA(A a) {
      this.a = a;
   }
}
Run Code Online (Sandbox Code Playgroud)