Making methods private
Private methods can also be used to make code modular by encapsulating logic into smaller, reusable methods that can be used. You will add a method to deploy airbags in the Car
class. You would not want this method to be one that can be accessed from the outside, for security reasons.
This exercise is part of the course
Introduction to Object-Oriented Programming in Java
Exercise instructions
- Create a
private
method calleddeployAirbags
as avoid
method that takes no parameters. - Inside the
deployAirbags
method, print out the message"airbags deployed"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class Main {
static class Car {
public String color;
public String model;
public int year;
private int vehicleNumber;
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
this.vehicleNumber = 101189;
}
// Create deployAirbags method
___ ___ ___() {
___.___.___(___);
}
public void turnEngineOn() {
System.out.println("engine is on");
}
public int calculateMPG(int milesDriven, int gallonsUsed) {
return milesDriven / gallonsUsed;
}
}
public static void main(String[] args) {
Car myCar = new Car("red", "camry", 2022);
}
}