Car.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class Car { public int maxSpeed = 200; public int price = 100000; /** * @return the maxSpeed */ public int getMaxSpeed() { return maxSpeed; } /** * @param maxSpeed the maxSpeed to set */ public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } /** * @return the price */ public int getPrice() { return price; } /** * @param price the price to set */ public void setPrice(int price) { this.price = price; } } |
CarFactory.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class CarFactory { public static void main(String[] args) { Car car = new Car(); car.maxSpeed = 250; //valid but bad programming. System.out.println("Car max speed is: " + car.maxSpeed ); //valid but bad programming. car.setMaxSpeed(200); System.out.println("Car max speed is: " + car.getMaxSpeed()); /*** Lets see how car price behaves***/ car.setPrice(1050000); System.out.println("Car price is: " + car.getPrice()); //compile error: private modifier protect instance variable to access directly from other class //private modifier do will not allow to set or get the price directly from out of class. car.price = 2000000; System.out.println("Car price is: " + car.price); } } |
Output:
1 2 3 4 5 6 | Car max speed is: 250 Car max speed is: 200 Car price is: 1050000 Car price is: 2000000 |
Encapsulation in java is a process of wrapping code and data together into a single unit.
The Java Bean class is the example of fully encapsulated class.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
Benefits of Encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.