-4

I have 2 Java classes car and camion (this is just an example). And I would like to initialise a variable "machine" depending on my function input:

void printInfo(boolean is_car){
       if(is_car)
                car machine = new car();

       else
                camion machine = new camion();
       
       String info = machine.getInfo();
       String type = machine.type();
       ...

}

It seems that I can't use the declared variables outside the if statement. Is there any solution for that? I would like to avoid putting lot of If statements in my function.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
zero
  • 43
  • 4
  • 2
    If they have inheritance relationship you can change a little to make this work. If not, that would be a horrible practice for a strongly typed language, and you should avoid it at all cost. – Bing Wang Apr 30 '21 at 23:48
  • 1
    The variable would be immediately out of scope, so an if doesn't allow variable declaration (unless enclosed in a block). See also [Compiler error when declaring a variable inside if condition and no curly braces](https://stackoverflow.com/questions/9206618/compiler-error-when-declaring-a-variable-inside-if-condition-and-no-curly-braces) – Mark Rotteveel May 01 '21 at 10:35

1 Answers1

1

Declare Vehicle (suppose which is super class of both car and camion) outside of the if block.

Vehicle machine;
if (is_car) {
    machine = new car();
} else {
    machine = new camion();
}
hata
  • 11,633
  • 6
  • 46
  • 69