簡體   English   中英

同時調用類的Java

[英]Java calling of classes simultaneously

有兩個具有主要功能的java類。 現在,我必須將第一類的對象稱為第二類,並將第二類的對象稱為第一類。 每當我這樣做時,都會給出堆棧溢出異常。 有什么方法可以同時調用這些方法嗎?

頭等艙:

 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();

第二類:

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();

您將進行遞歸,其中類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();
}

用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;
   }
}

用ForgotPassword和ChangePasswordLoging代替A和B。

或者,您也可以像下面的代碼那樣,小心地創建每種類型的一個實例:

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;
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM