Creating private properties
Class properties are often made private to restrict external access. For instance, in a Passport class, certain fields should be set only under specific conditions. You will make a car’s registration number private in the Car
class to hide it.
Este exercício faz parte do curso
Introduction to Object-Oriented Programming in Java
Instruções do exercício
- Create a new
private
property calledvehicleNumber
that is anint
type.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
class Main {
static class Car {
public String color;
public String model;
public int year;
// Create private property "vehicleNumber"
___ ___ ___;
Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
this.vehicleNumber = 101189;
}
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) {
}
}