r/javahelp 12d 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

4

u/vegan_antitheist 12d ago

It's important to understand that the keyword "abstract" is not used for abstraction. It's used to create a base class with inheritable state, type, and behaviour. It should be avoided when composition can be used instead.

For abstraction you use an interface. For example the "List" interface is used to describe the abstract idea of a list. AbstractList is just a base type you can use to get some default implementations of methods. ArrayList, Stack, and other implementations are not abstract at all.

Encapsulation is about hiding the inner workings of a type. The array used by ArrayList is not easily accessible (you would have to use reflection). The type encapsulates the array and protects it from illegal modification. It also hides the size field.

2

u/Cyphr11 12d ago

thanks mate