calling a class from another without a StackOverFlowError occurring

-2

Greetings,

I have a program divided by packages and I also divide the logic of the interface, I am using the DAO and Factory models.

I have some Get methods within a JFrame - I'll call it Class A - that refer to text fields, access to these methods Get from another class that has a Save method - this one I'll call Class B -.

The problem arises because I created an instance of Class A in Class B to access the Get methods of JFrame and save the information.

Likewise, I created an instance of Class B in Class A to call the Save method within a button.

>

Because I repeatedly call two objects, a circular dependency error is created between A and B leading to a StackOverFlowError . . p>

My question is: how can I call the two classes without this error occurring?

    
asked by David Calderon 12.06.2016 в 18:11
source

2 answers

1

Apparently you have a problem with circular dependencies. For the type of error you have, StackOverFlowError , it seems you have something like this:

public A() {
   b = new B();
}

public B() {
   a = new A();
}

This simply makes an infinite recursion of instantiation of A and B, so it will produce a StackOverFlowError .

Instead of builders you can use setters to associate objects with each other.

    
answered by 12.06.2016 в 19:41
1

When you create an instance using the reserved word new the constructor method is called, so if you instantiate the same class inside the constructor you generate an infinite loop.

The default constructor method returns a class instance so you do not need to call it again.

It is not clear to me why you want to create an object of the same class that you are instantiating and save it as an attribute, but you could use the reserved word this to refer to the created instance.

Objeto v;

public Constructor() {
 this.v= this;   
}
    
answered by 12.06.2016 в 20:19