Get startedGet started for free

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.

This exercise is part of the course

Introduction to Object-Oriented Programming in Java

View Course

Exercise instructions

  • Create a new private property called vehicleNumber that is an int type.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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) {
    	
    }
}
Edit and Run Code