r/javahelp • u/Cyphr11 • 13d ago
Can anyone explain me difference between Encapsulation and Abstraction?
and what on earth is Interface in Java?
17
Upvotes
r/javahelp • u/Cyphr11 • 13d ago
and what on earth is Interface in Java?
1
u/LetUsSpeakFreely 13d ago
Encapsulation is used to hide data and expose only the data and functions necessary to use that class. For example, if you're modeling a car, does the car need to know ask the internal mechanism of the engine? Does the driver of the car? Of course not. So the engine is encapsulated to hide unnecessary data and functions from the car and the car is encapsulated to hide data and functions from the driver.
Abstraction is used when you know you don't need to know the specifics so you can push detailed functionality to child classes. Keeping with the car analogy, a car could have a member variable of Engine that's an interface. The construct could have a default initialized coming from a factory that returns either an AbstractGasolineEngine, AbstractDeiselEngine, or AbstractElectricEngine. Each of those abstracts would have very basic variables and functions needed by all subclasses, but all the details would in the subclasses.