concept car class in category java

This is an excerpt from Manning's book Get Programming with Java MEAP V04 livebook.
Figure 2.1 Code listing for the start of the Car class
![]()
Let’s revisit the Car class from Lesson 3 and update it with a getter and setter method for each piece of instance data. Listing 4.1 shows the code from lesson 3. Remember, each car object was given values for the following instance data:
Listing 4.2: Car Class with Getter and Setter Methods
1. public class Car { 2. private String make, model, color; 3. private int year; 4. private double mpg; 5. 6. public String getMake() { return make; } //#A 7. public String getModel() { return model; } //#A 8. public String getColor() { return color; } //#A 9. public int getYear() { return year; } //#A 10. public double getMPG() {return mpg; } //#A 11. 12. public void setMake(String make) { //#B 13. this.make = make; } 14. public void setModel(String model) { //#B 15. this.model = model; } 16. public void setColor (String color) { //#B 17. this.color = color; } 18. public void setYear (int year) { 19. if(year >= 1900 && year <=2050) 20. this.year = year; 21. else 22. System.out.println("Invalid year"); 23. } 24. public void setMPG(double mpg) { //#B 25. this.mpg = mpg; } //#B 26. 27. public void moveForward() { } 28. public void moveBackward() { } 29. public void stop() { } 30. public void turnLeft() { } 31. public void turnRight() { } 32. public void honk() { } 33. public static void main(String[] args) { 34. Car myCar = new Car(); 35. myCar.make = "Subaru"; 36. myCar.model = "Outback"; 37. myCar.year = 2017; 38. myCar.mpg = 28; 39. myCar.color = "black"; 40. } 41. }Now, the Car class has methods for retrieving the instance data about any car object and updating the data. By making these methods public, they can be used by this program and others. Also, notice that each getter method has a return type, so when the calling program uses these methods, it must expect the value returned to be the same data type.