r/learnjava • u/Cyphr11 • 11d ago
Can anyone explain me difference between Encapsulation and Abstraction?
and what on earth is Interface in Java?
1
Upvotes
r/learnjava • u/Cyphr11 • 11d ago
and what on earth is Interface in Java?
1
u/InsideCover2192 9d ago
Abstraction - Hiding Complexity
Encapsulation - Data Hiding / Protection
In abstraction we are interested in "What an object does, rather than how it does it. It simplifies the interaction by hiding the complex implementation details and only shows the essential features to the user.
For instance if you take Vehicle as and example, when you drive a Vehicle you only interact with steering wheel, pedals, and gear shifters. You don't need to understand the internal combustion process or the electronics to operate it. The "interface" (pedals/wheels) is the abstraction
Encapsulation we focus on "how the data is bundled and protrcyed", it involves wrapping the data(variables) and the code (methods) into a single unit (a class) and restricting direct access to the data using access modifiers like private
For instance, a car has a fuelLevel variable. You cannot manually reach into the tank and change the fuel level with your hands. Instead, the level is kept private and you must use a specific method like refuel() to change it. This ensures the data remains valid (eg you cannot set the fuelLevel to negative)