Using Getters and Setters


/ Published in: Java
Save to your folder(s)

This lab #2 from my Programming with Java class


Copy this code and paste it in your HTML
  1. public class Bicycle
  2. {
  3. private int cadence;
  4. private int gear;
  5. private int speed;
  6.  
  7. public Bicycle(int startCadence, int startGear, int startSpeed)
  8. {
  9. cadence = startCadence;
  10. gear = startGear;
  11. speed = startSpeed;
  12. }
  13.  
  14.  
  15. public int getCadence()
  16. {
  17. return cadence;
  18. }
  19.  
  20.  
  21. public void setCadence(int cadence)
  22. {
  23. this.cadence = cadence;
  24. }
  25.  
  26.  
  27. public int getGear()
  28. {
  29. return gear;
  30. }
  31.  
  32.  
  33. public void setGear(int gear)
  34. {
  35. this.gear = gear;
  36. }
  37.  
  38.  
  39. public int getSpeed()
  40. {
  41. return speed;
  42. }
  43.  
  44.  
  45. public void setSpeed(int speed)
  46. {
  47. this.speed = speed;
  48. }
  49.  
  50.  
  51. public void ApplyBrake(int decrement)
  52. {
  53. speed -= decrement;
  54. }
  55.  
  56. public void speedUp(int increment)
  57. {
  58. speed += increment;
  59. }
  60.  
  61.  
  62. public void PrintValues()
  63. {
  64. System.out.println("Gear = " + gear);
  65. System.out.println("Cadence = " + cadence);
  66. System.out.println("Speed = " + speed);
  67. System.out.println("");
  68. }
  69.  
  70. public static void main(String [] args)
  71. {
  72. Bicycle myBike = new Bicycle(30,0,1);
  73. System.out.println("Bicycle Parameters");
  74. System.out.println("===================");
  75. myBike.PrintValues();
  76.  
  77. myBike.speedUp(30);
  78. myBike.setGear(2);
  79.  
  80. System.out.println("New Bicycle Parameters");
  81. System.out.println("=======================");
  82. myBike.PrintValues();
  83. }
  84.  
  85.  
  86. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.