Java Encapsulation: Implementing Car Class with Getter and Setter Methods
Write a Java program to create a class called Car with private instance variables company_name, model_name, year, and mileage. Provide public getter and setter methods to access and modify the company_name, model_name, and year variables. However, only provide a getter method for the mileage variable.
Sample Solution:
Java Code:
Output:
Company Name: Chevrolet Model Name: Cruze Year: 2009 Mileage: 0.0
Explanation:
In this code, the Car class encapsulates the private instance variables company_name, model_name, year, and mileage. The getCompany_name(), getModel_name(), and getYear() methods are public getter methods that allow other classes to access company_name, model_name, and year, respectively. The corresponding set methods are provided to modify these variables.
The getMileage() method is a public getter method that allows other classes to access mileage values. However, no setter method is provided for mileage, meaning it cannot be modified outside the Car class.
In the Main class, an object car of the Car class is created. Company_name, model_name, and year values are set using the respective setter methods, and then retrieved using the getter methods.
The mileage is then retrieved using the getMileage() method and printed using System.out.println().
Flowchart:



For more Practice: Solve these Related Problems:
- Write a Java program where the "Car" class prevents setting a year before 1886 (year of the first car).
- Write a Java program where the "Car" class includes a method to calculate fuel efficiency.
- Write a Java program where the "Car" class allows updating the mileage only through a drive method.
- Write a Java program where the "Car" class supports setting a maximum speed limit.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Implementing a circle class with getter, setter, and calculation methods.
Next: Implementing a Student Class with Grade Validation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.