Mary
Mary

Reputation: 43

How to get a result from a void method from another class

In Class1 we have a method:

 public void check(String username, String password) {

   if (username and password are correct) {
         message = "checked"; 
   } else
   {
     message = "not checked";
   }
}

In Class2 we have a method doPost and then we do this :

Class1 cl = new Class1();
cl.open();
cl.check(username,password);
cl.close()

In class Error I would like to show the message, which is in Class1. Maybe with one Dispatcher? Which is the most efficiency way to make it?

Upvotes: 0

Views: 1146

Answers (2)

void
void

Reputation: 7880

Surely there are much better ways for that, but if you don't want to change your solution as you are setting a message in Class1, you should be able to access to that message in Class2, so create getter and setter for the message variable and access the message via getter(and setters):

in Class1:

public String setMessage(String message){
   this.message=message;
}
public String getMessage(){
   return message;
}

public void check(String username, String password) {

   if (username and password are correct) {
         message = "checked"; 
   } else
   {
     message = "not checked";
   }
}

in Class2:

Class1 cl = new Class1();
cl.open();
cl.check(username,password);
cl.close();
out.println(cl.getMessage());//or anything else(you have access to generated  message)

Upvotes: 2

Sasha Pachev
Sasha Pachev

Reputation: 5326

You can throw an exception in check() if the check fails.

Upvotes: 0

Related Questions