What is encapsulation in java with example?
1 answer(s)
Answer # 1 #
Encapsulation is a core concept in Java, mate. Think of it as bundling an object's data and methods into a single unit. It's all about data hiding.
You declare your class variables as private. This stops other classes from directly messing with them. Instead, you provide public methods (getters and setters) to control how the data is read or changed. This gives you full control.
For example, a BankAccount class would keep its balance variable private. To add money, you'd have to call a public deposit() method, which can check that the amount is a positive number.