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.
Cet exercice fait partie du cours
Introduction to Object-Oriented Programming in Java
Instructions
- Create a
privatemethod calleddeployAirbagsas avoidmethod that takes no parameters. - Inside the
deployAirbagsmethod, print out the message"airbags deployed".
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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
____ ____ deployAirbags() {
System.out.println("____");
}
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);
}
}