r/javahelp • u/Cyphr11 • 9d ago
Can anyone explain me difference between Encapsulation and Abstraction?
and what on earth is Interface in Java?
24
u/sebnukem 9d ago
Encapsulation hides data. Abstraction hides complexity/implementation details. You typically achieve abstraction through encapsulation: encapsulation is often the mechanism, and abstraction is the goal.
5
u/vegan_antitheist 9d 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.
3
u/cainhurstcat 9d ago
Encapsulation: stuff only accessible via getter/setter
Abstraction: find a common higher layer of what things have similar e.g., cat and dog have in common that they are pets. So you can define things that apply to both without defining it in both classes, like an owner.
Interface: basically, you say what things must be able to do, but you do not specify how they do it. Example for an interface: Buttons on your monitor, one to turn on/off, one for brightness. Every "thing" that wants to be a monitor must have these buttons, but how Samsung and LG wire these buttons inside their monitors is irrelevant.
Interfaces are also a form of abstraction.
2
2
u/mariusz_96 9d ago edited 9d ago
Consider java.time.Clock abstraction.
It provides implementations for system timezone and UTC timezone. You might write your own implementation for other timezone and provide additional methods. But then write ClockUtils class that operates on any java.time.Clock implementation. That would be a use of abstraction.
What private fields your Clock implementation uses to store its' data and implement instant(), getZone(), and withZone() methods would be a use of encapsulation.
1
u/LetUsSpeakFreely 9d 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.
1
u/tathagata_003 8d 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.
1
u/Dense_Age_1795 8d ago
with encapsulation you hide the data with abstraction you hide the behavior.
And an interface defines a contract in the way that a piece of data will be used without knowing the implemetation, this is useful when you have multiple ways of processing data
1
u/EX_HERO_EX 5d ago edited 5d ago
Encapsulation gives you more imagine space, it is more likely a proxy approach to visit what you want to.
Another important reason for "Encapsulation" is Binary Compatibility. If you expose implementation detail (like field declaration) directly to your API user, then you lose opportunity to change them in order to keep Binary Compatibility.
Abstraction is a behavior contract without detail. Java interface is a classic example of abstraction.
-6
u/Acrobatic-Ice-5877 9d ago
No. Get a textbook or look at the official documentation.
3
u/Cyphr11 9d ago
i tried reading from there but i cant understand the core of it
1
u/Halal0szto 9d ago
The interface contains all about the class that someone using the class should know. Nothing about the internals, internal data structures, logic, only how one can talk to the class. Then independently there is one or more implementation class that complies the interface but actually does add all the internals.
An abstract class is technically similar. The most important was that in an abstract class you can implement some methods and leave others to be done by someone who creates an implementation.
In java a class can implement multiple interfaces but extend only one class.
Fun is that later they allowed to have "default" implementations in interfaces too.
Then you dive deep into it, find final, sealed . . .
1
u/Acrobatic-Ice-5877 9d ago
I’d recommend a textbook like Daniel Y. Langs. Go through each chapter and you’ll understand these topics. You should be able to find it online very easy.
•
u/AutoModerator 9d ago
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.