As far as I know Java has automatic casts for transforming compatible data types from smaller to larger since no data is lost, yet in one of the test programs in my JDK 8 beginners guide book, a cast is used this way. The method fuelNeeded is of question. I know it prints the same double result without the cast so why is this needed? Or is it?
class Vehicle {
int passengers;
int fuelcap;
int mpg;
Vehicle (int p, int f, int m) {
passengers = p;
fuelcap = f;
mpg = m;
}
int range() {
return mpg * fuelcap;
}
double fuelNeeded(int miles) {
return (double) miles / mpg;
}
}
public class CompFuel {
public static void main(String[] args) {
Vehicle minivan = new Vehicle(7, 16, 21);
Vehicle supra = new Vehicle(2, 14, 12);
double gallons;
int dist = 252;
gallons = minivan.fuelNeeded(dist);
System.out.println("To go " + dist + " miles, minivan needs " + gallons + " gallons of fuel");
gallons = supra.fuelNeeded(dist);
System.out.println("To go " + dist + " miles, supra needs " + gallons + " gallons of fuel");
}
}