0

Hopefully, the following will make sense. I have a program with a superclass called vehicle. There are three classes that extend this class, tank, chopper and boat.

In my code, depending on what option the user chooses will create an instance of that class. The vehicle class has a method in it for setting up the stats called setStats(). The problem is, that when I try to call this method, my code won't compile because the instance of the object is created in the if statement.

        if (P2Type == "Tank") {tank p2 = new tank();};
        if (P2Type == "Boat") {boat p2 = new boat();};
        if (P2Type == "Chopper") {chopper p2 = new chopper();};

        //main game
        //set stats
        p2.setStats();

I know that you would normally set the data type of a variable outside of the if statement, but because this variable could be one of three options, I am not really sure how to get around this problem. Grateful for any advice.

Robert Flook
  • 307
  • 6
  • 12
  • Also relevant: [How do I compare Strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – maloomeister May 04 '21 at 11:04
  • Also, don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels May 04 '21 at 11:04
  • Your problem is one of "variable scope" where all the variables declared within their if statements are not visible outside the statements. The best solution is probably to declare a parent-type variable before the if statements, perhaps `Vehicle selectedVehicle = null;` and assign it within your if statements or switch statement – Hovercraft Full Of Eels May 04 '21 at 11:05
  • yeah, it better to use P2Type.equals("Tank") insted of P2Type == "Tank" – Belaid BOUAOUALTEN May 04 '21 at 11:09

0 Answers0