Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Introduction to Object-Oriented Programming in Java

Cursus bekijken

Oefeninstructies

  • Create a private method called deployAirbags as a void method that takes no parameters.
  • Inside the deployAirbags method, print out the message "airbags deployed" .

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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);        
    }
}
Code bewerken en uitvoeren