ComeçarComece de graça

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.

Este exercício faz parte do curso

Introduction to Object-Oriented Programming in Java

Ver curso

Instruções do exercício

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

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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);        
    }
}
Editar e executar o código