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:
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.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.Type Inference: The type inferred is the exact type of the initializer. For example, if you assign an
ArrayList<String>
to a variable declared withvar
, the variable will be of typeArrayList<String>
.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. Usevar
judiciously to maintain clear and understandable code.Cannot be
null
: The initializer for avar
cannot benull
alone, since the type would be ambiguous.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