Module 8 Lab - Travel Mode (State Pattern)

Provide the classes 1) Drive and 2) Bicycle and demonstrate their usage in the Lab1 driver using the starter code below:

Final Solution UML:

Code Starter

TravelMode.java

package StatePatternLabOne; public interface TravelMode { Object getETA(); Object getDirection(); }

Walk.java

package StatePatternLabOne; public class Walk implements TravelMode { @Override public Object getETA() { System.out.println("Calculating ETA (walking)"); return 4; } @Override public Object getDirection() { System.out.println("Calculating Direction (walking)"); return 4; } }

Bus.java

package StatePatternLabOne; public class Bus implements TravelMode { @Override public Object getETA() { System.out.println("Calculating ETA (transit)"); return 3; } @Override public Object getDirection() { System.out.println("Calculating Direction (transit)"); return 3; } }

DirectionService.java

Driver.java (driver)

In Java, the keyword var is used to enable local variable type inference. This means that you don't have to declare the variable type explicitly; instead, the compiler infers the type based on the value assigned to the variable. var was introduced in Java 10 to enhance the language's conciseness and readability.

Here are some important points to keep in mind when using var in Java:

  1. Local Variables Only: var can only be used to declare local variables within methods or blocks. It cannot be used for fields, method parameters, or return types.

  2. Initialization Required: A variable declared with var must be immediately initialized. This initialization is necessary because the variable type is inferred from the type of the initializer expression.

  3. Type Inference: The type inferred is the exact type of the initializer. For example, if you assign an ArrayList<String> to a variable declared with var, the variable will be of type ArrayList<String>.

  4. Readability: While var can make code less verbose, it can also make it less readable in cases where the type could be more obvious from the initializer. Use var judiciously to maintain clear and understandable code.

  5. Cannot be null: The initializer for a var cannot be null alone, since the type would be ambiguous.

  6. No Polymorphic Behavior: If the expression on the right-hand side of the declaration is a polymorphic type, var will adopt the exact type, not the interface or the superclass.

Current Output:

 

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark