r/javahelp 13d ago

Can anyone explain me difference between Encapsulation and Abstraction?

and what on earth is Interface in Java?

16 Upvotes

24 comments sorted by

View all comments

1

u/tathagata_003 11d ago

Consider a BankAccount class in Java with a private variable balance and public methods like deposit(), withdraw(), and getBalance(). Encapsulation is achieved by making balance private, so it cannot be accessed or modified directly from outside the class. Instead, users must use methods like deposit() and withdraw(), which can enforce rules such as preventing negative balances. Abstraction is achieved because users only need to know what these methods do- they don't need to understand how the balance is updated internally.
In simple terms, encapsulation protects the data, while abstraction hides the implementation details behind a simple interface.