Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. package OOP.Polymorphism.Vehicles;
  2.  
  3. import java.text.DecimalFormat;
  4.  
  5. public abstract class Vehicle {
  6.  
  7. private double fuelQuantity;
  8. private double fuelConsumption;
  9. private double tankCapacity;
  10.  
  11.  
  12. public Vehicle(double fuelQuantity, double fuelConsumption, double tankCapacity) {
  13. this.setFuelConsumption(fuelConsumption);
  14. this.tankCapacity = tankCapacity;
  15. this.fuelQuantity = fuelQuantity;
  16. }
  17.  
  18. protected double getFuelConsumption() {
  19. return this.fuelConsumption;
  20. }
  21.  
  22. protected void setFuelConsumption(double fuelConsumption) {
  23. this.fuelConsumption = fuelConsumption;
  24. }
  25.  
  26. public String drive(double distance) {
  27. String output;
  28. double fuelNeeded = distance * this.getFuelConsumption();
  29. if (fuelNeeded <= this.fuelQuantity) {
  30. this.fuelQuantity -= fuelNeeded;
  31.  
  32. DecimalFormat format = new DecimalFormat("#.##");
  33.  
  34. output = String.format("%s travelled %s km", this.getClass().getSimpleName(),
  35. format.format(distance));
  36.  
  37. } else {
  38. output = String.format("%s needs refueling", this.getClass().getSimpleName());
  39. }
  40.  
  41. return output;
  42. }
  43.  
  44. public void refuel(double fuelQuantity) {
  45. if(fuelQuantity + this.fuelQuantity > this.tankCapacity) {
  46. throw new IllegalArgumentException("Cannot fit fuel in tank");
  47. }else if(fuelQuantity <= 0) {
  48. throw new IllegalArgumentException("Fuel must be a positive number");
  49. }
  50. this.fuelQuantity += fuelQuantity;
  51. }
  52.  
  53. @Override
  54. public String toString() {
  55. return String.format("%s: %.2f",this.getClass().getSimpleName(),
  56. this.fuelQuantity);
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement