Home > Software design >  Object declaration check in Java
Object declaration check in Java

Time:03-01

My code snippet:

if (answer) {
 TourRequest tour = new TourRequest();
}

After the above statement, I want to declare tour object, using a different constructor if it hasn't already been declared inside the curly brackets.

How can I check directly if tour exist, without using the content of the answer variable?

CodePudding user response:

Declare the variable outside of the if statement and then check if it is null.

TourRequest tour = null;
if(answer) {
  tour = new TourRequest();
}

if(tour == null) {
  tour = new TourRequest(/*params...*/);
}

Better yet, just use an else.

TourRequest tour;
if(answer) {
  tour = new TourRequest();
}
else {
  tour = new TourRequest(/*params...*/);
}

CodePudding user response:

the simplified solution is here

TourRequest tour = answer ? new TourRequest() : new TourRequest(parameter);
  • Related