In our encapsulation example we will create 3 classes:

Color

Car

And Manufacturer

 

In color Class there will be 2 private read-only fields containing colors and two public methods to access them. Fields will be private read-only because we do not want someone to access or change their values, and methods will be public because we want to access values from our fields.

 

Car class will also contain 2 private fields but with car model names and two public methods which can access our fields, but we will also create two public static integers whose values we will access and alter in Manufacturer class.

 

Manufacturer class will access methods from Color and Car classes and alter one of static integers from Car class.

Encapsulation example: