#What is Encapsulation?
1 messages ยท Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
https://docs.oracle.com/javase/tutorial/java/concepts/object.html
Oracle uses definition one for data encapsulation
This beginner Java tutorial describes fundamentals of programming in the Java programming language
first one
My institute gave me a book ( Core and Advanced Java Black Book Dreamtech Press ) and it has this definition
Is it correct one to speak in an interview
Also for abstraction , it says this definition , I always thought abstraction meant hiding implementation details
yes ? what is the problem ? it is still the first one ?
yes ?
I was just cross verifying the definition , for some reason the picture is coming small
Just cross verifying
both are
encapsulation started with "encapsulating data", putting data into some capsule
but for OOP, objects shouldnt be seen as data capsules
hence why it evolved to "hiding information" for modern OOP
what about abstraction?
if you have a baseball, a basketball, and a soccer ball, you can create an abstraction Ball which defines the similarities
But the definition the book gave called hiding data that is not required to be shown
a sports player may need to view the object as a Football
but stores may only care to view it as a Ball
thats encapsulation
See this here
yeah, abstraction can "hide details", but thats a confusing way to put it
its more that it "abstracts away details"
a Football will always be a Football. but sometimes, we only care about viewing it as a Ball
when viewing as a Ball, all the details of Football is abstracted away
because they arent needed in that situation
so its more like "simplifying"
hide data that is not required by the user
bad phrasing IMO
because thats how people get abstraction & encapsulation confused
they are not wrong, abstraction does get rid of details in a way
but how these concepts are presented make a huge difference when it comes to understanding them
encapsulation is "hide stuff", abstraction is "view something in a more simplistic way"
with abstraction, you arent really "hiding", because you can always use language features like casting to access the more complex type (if using Ball, could cast it to Football to view it as a foot ball)
with encapsulation, you need to use a special API to dive into the internals
"hide the internals" is encapsulation, "simplify the interface" is abstraction
abstraction does not hide internals
a TV for example. it hides all its circuits and stuff. thats encapsulation
but sometimes, we wanna view a TV in a more abstract way, maybe as an Electronic
@hollow locust I thought Arrays.sort() is abstraction
Hiding the implentation of sorting technique
the abstraction is Comparator
thats what abstracts the different comparing techniques used with that sort
another thing?
do we achieve encapsulation using setter , getter or any public function that can access private members will be called as encapsulation?
its not really encapsulated if they are "dumb" getters and setters. If you have a class Bill and it has private fields grossPrice and vatRate and a method getTotal that gives you grossPrice + grossPrice * vatRate then that would "hide" or "encapsulate" the internals.
yeah i was having a debate with my friend , he said getters and setters are not the only way to achieve encapsulation , if you have a mathematical function that changes data like in
Class{
int a ;
public void modifyX(){
a+=2;
}
}
This is also encapsulation apparently
getters and setters are usually harmful for encapsulation becuase they just give access to the state
Then why are they used?
I thought they are used explicitly so that we can access the state
because u dont need to encapsulate everything
yes and encapsulation is about not letting everyone access the state
and every detail about the class
why is this so confusing
sometimes u need to give access to state other times you want to hide it
allways depends on the usecase
you want to hide data from inside the class
so all fields are private, and you use getters and setters, but only for fields that need to be shared
can anything other than getters and setter be used?
and would that be called encapsulation?
theres a whole topic about that on the stack exchange
no, getters/setters do not provide proper encapsulation for OOP
then what provides proper encapsulation?
Can anyone point me to a good article I can read and clear all these doubts
you need to understand how objects are intended to be used in OOP
objects are made up of 2 things: state and behavior
Objects share two characteristics: they all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).
Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation
by defining getters/setters for everything, you are exposing the state of the object
instead, you should define how an object should be interacted with via behaviors
and users of that object should interact via the behaviors the object has, not the state
that doesnt mean all getter/setters are bad
it means you need to think about how users should interact with the object
So , not touch the state at all?
thats the idea
things that users have access to cant be changed
if you change things people are accessing, it could risk breaking their code
the more that is hidden, the more you can change
doesnt mean all getter/setters are bad either. just means "think about how users should interact"
and keep it as minimal, strict to that idea, as possible
so why we use getter setters?
I guess monkey see monkey do really hampered from deeply understanding these stuff
thats more of a procedural approach
its a form of encapsulation for procedural code, not OOP
this post focuses on that exact worry
"if we use getters setters, is it encapsulation?"
If you expose all your attributes with getters/setters you are gaining just data structure which is still used in C or any other procedural language. It is not encapsulation
objects arent meant to be seen as data structures, unless they are specifically designed to be a data structure
objects should be seen as things that can be interacted with via behaviors, like irl
Probably a bad time to learn all of this , just 4 hrs remaining for interview
should have asked sooner ๐คทโโ๏ธ
this is an official reference, from Oracle themselves
think in terms of state & behavior
hide state, expose behavior
thats encapsulation
and an object's methods define it's behaviors
I see , I guess I just never questioned it much cause everyone just said the same definitions around me
- Encapsulation - > Binding data and functions together
- Abstraction -> Hiding implementation details
- Inheritance -> Inheriting properties of parent class
- Polymorphism -> Many forms
not bindind data & functions, rather "hiding state"
otherwise, thats a decent simplification
my issue is , if I go with the hiding state to interview , the interviewer might get confused
I will just say both definitions if I remember it that time
if the interviewer gets confused about that, run
if they question you about OOP, yet dont understand OOP themselves, thats a red flag
i have been unemployed for over 1.5 years , i don't wanna throw any opportunity
just keep it in your pocket
if they dont like the answer you give, they may be looking for "hide state, expose behaviors"
"state should only be modified via behaviors"
thats what my last 2 Forwards summarize, all from an official source
not all methods are public either
you might have a method that is broken down into many other methods. those sub-procedures/methods may be private
and thats also encapsulation
its data hiding
yeah I got it now , an object has a state and we change it using behaviours of the object
Like bike has gear and we can changeGear() to use gear
can use changeGear() to change the gear state
and that may seem like a setter
the difference is, its an intended behavior, well defined
opposed to some blindly-written setter
we need to change gears on a bike
so thats a behavior. even though it may act as a setter, its defined as a behavior
and thats where interfaces play a role
and abstraction?
Do you have a definition you can give?
I only know -> Hiding Implementation details , but that is basically Encapsulation
lmao this isnt a 10 minute topic
it stays true to its original definition, which is
existing in thought or as an idea but not having a physical or concrete existence
there are pufferfish, clown fish, etc...
but then we have the abstraction "Fish"
its an idea
"Fish" is a simplification
its an abstract concept, its a category in a sense
but its not concrete. it lacks details
I am just going with -> Generalizing Concrete details and give example of ball , fish etc..
its one thing to say "i know this", its another thing to be questioned & not know the answers (not understanding)
generalizing, yeah
thats a good word for it
its a generalization. there are "spoons", there are "forks"
we generalize them as "Eating Utensils"
abstraction is generalizing concrete concepts into abstract concepts ?
how about this?
idk, im not the interviewer ๐
if i was, id be like "yeah this person doesnt really know"

generalization is a good word. "simplifying how we view something" is another
I am doomed
In software engineering and computer science, abstraction is the process of generalizing concrete details,[1] such as attributes, away from the study of objects and systems to focus attention on details of greater importance
Wikipedia definition
yes, it does give the appearance of hiding info, since all the info of TV wont be available when viewing it as an Electronic
Dog dog = new Dog();
// can give bone
// can do dog things```
Animal animal = new Dog();```
animal still references a Dog object. but by using the Animal type, you dont get access to all the dog things
instead, you only view it in terms of an animal
hope this helped in some way
in the end, you need experience with it to truly understand
because even though you may know the theory, they may want a code example
True
got 4 hours
start cramming
ask as many questions here
understand the theory
but also understand the application, dive into how its handled in code
its possible too
ive had to cram more in less time for my first biology thesis ๐ญ
so you gotta jump in
Well it's a Java Interview so Idk where they would ask , I looked at Glassdoor and they say they do ask from OOPs concept
Company name is AumniTechworks
Bond of 18 months
never heard of them
all i know is that they're based in India and have a pool table
i am based in india too
none of that is going to help you better understand these concepts
and time is ticking. gotta either practice, or ask questions
are comparable and comparator the same thing?
From what i have praticed comparable is something that a class implements
Comparator is the external sorting
a comparator makes the comparisons. a comparable can be compared with
so a String is comparable
you can compare strings to other strings
so String implements Comparable
it is comparable
but you might have a system that performs the actual comparing, like a sorting algorithm
the sorting algorithm would require a comparator
that way it knows how to sort the comparables
from least to great? by name? by age?
but the interview question part also dives into hashcode
how long did you procrastinate? ๐
cause this is a lot
I didn't, why you ask?
Dude i don't have concepts on my fingertips
because youre asking about the 4 pillars of OOP
but the image mentions DSA & hashcodes
collections
yeah , i was checking glassdoor , it said , company asked some person this , idk what the interviewer will ask me
march 2024
id assume theyd ask similar questions
DSA is a 101 topic for computer science
It's 6am in the morning , I am awake all night , interview at 9:30am , oh well , let's see , it all depends on luck now
not luck, studies
start asking questions, or start practicing
those are the two options rn
the only "luck" would be what interviewer you get. but if you know the stuff, it wont matter
i am already doing that
Okay , so I want to know , what does Serializable does
I only know theory , it helps in persisting object into database
and if you're gonna be working on tech ima use, id hope you know the stuff ๐
it could persist into a database, yeah
but thats not it's usecase, and its abuse of the system to do that
because serializable data should be transient
it should exist temporarily, only to be sent over some kind of network
if you persist it, many issues arise
serializable allows an object to be converted into bytes, typically to be transferred over a network
you could persist that data, but thats not the intended usecase, and could cause problems
heres an SO answer i wrote a few years back explaining it
someone asked "Why should we minimize the use of Serializable"
im pretty sure Java is deprecating their current serialization system. if not now, in the future
theyve talked about it
serialization is the main topic
turning an object into bytes, to be transferred somewhere
transferred to persistence? not good
transferred to another machine/service, where the serialized data only exists temporarily? yeah
over a network of some sort
transient
The ability to store and retrieve JavaTM objects is essential to building all but the most transient applications.
Okay , so serialization is basically converting objects into bytes , there can be many use case , like writing into a file and mostly transferring over a network
I see a lot of these issue comes from a lack of practice
yup
you can use it for persistence, but theres a good reason why it isnt used for that (outlined in my SO post)
I will read it , here is another one
How does compareTo figure how to sort something in ascending or descending order?
it returns -1, 0, or 1
0 is equal
this is where JavaDocs come in handy
declaration: module: java.base, package: java.lang, interface: Comparable
Yeah I know , positive if a>b , negative if a<b
but here i ask , how?
I tried looking inside the compareTo method , it went completely over my head
go down to compareTo
it depends on whats being compared
for integers, its pretty straight forward
How many experience do you have in Java?
I am a fresher , that should be obvious
go to the return section of compareTo
negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
15 years professional, about 5 years non-professional
so around 20 years in total
regardless, you should always rely on official sources, which is why im trying to provide them as we go
compareTo receives a value, compares it to the current value
if the current value is less than the received value, you return -1
class NumberHolder implements Comparable<NumberHolder> {
int number;
public int compareTo(NumberHolder otherHolder) {
if(this.number < otherHolder.number)
return -1
else ...
}
}```
might be a lot to take in
this is why practice matters
youre right
when it comes to things like String, its up to whoever designs the class
whoever designed String decided the comparison should be lexicographic
if you looked at the JavaDocs for String#compareTo:
Compares two strings lexicographically
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class Food implements Comparable<Food>{
String name;
Integer quantity;
public Food(String name, Integer quantity){
this.name = name;
this.quantity = quantity;
}
@Override
public int compareTo(Food o) {
return name.compareTo(o.name);
}
}
public class ComparatorVsComparable {
public static void main(String[] args) {
List<Food> foodList = Arrays.asList(new Food("Mango",10),new Food("Apple",5),new Food("Guava",15));
Collections.sort(foodList);
for(Food food : foodList) System.out.println("Name : " + food.name + " Quantity : " + food.quantity);
}
}
Okay I just wrote this code
In collections sort, class food is using it's comparable interface that I implemented
So here , it will compare Mango with Apple and change it in asc order right?
you tell me. does the output give that?
Yeah
found the answer yourself
thats a sign of a true dev
sometimes you gotta go to the whiteboard, test things out
Okay , so I am tinkering with the code
Instead of comparable I am using comparator and it is giving an error
whats the error message?
21:20
java: no suitable method found for sort(java.util.List<Food>)
method java.util.Collections.<T>sort(java.util.List<T>) is not applicable
(inference variable T has incompatible bounds
equality constraints: Food
upper bounds: java.lang.Comparable<? super T>)
method java.util.Collections.<T>sort(java.util.List<T>,java.util.Comparator<? super T>) is not applicable
(cannot infer type-variable(s) T
(actual and formal argument lists differ in length))
import java.util.*;
class Food implements Comparator<Food> {
String name;
Integer quantity;
public Food(String name, Integer quantity){
this.name = name;
this.quantity = quantity;
}
@Override
public int compare(Food o1, Food o2) {
return o1.name.compareTo(o2.name);
}
}
public class ComparatorVsComparable {
public static void main(String[] args) {
List<Food> foodList = Arrays.asList(new Food("Mango",10),new Food("Apple",5),new Food("Guava",15));
Collections.sort(foodList);
for(Food food : foodList) System.out.println("Name : " + food.name + " Quantity : " + food.quantity);
}
}
After this I will most probably check out multithreading
If possible Serialization a bit as well
Reflection is also left
F*ck me
stick to the interview stuff first lmao
So much for a fresher interview
damn
got a lot
Collections.sort(List) expects Food to be a Comparable
its defined as sort(List<T>)
T is defined as <T extends Comparable>
so T must be Comparable
theres another method though, Collections.sort(List, Comparator)
sometimes you have a list of things that dont implement Comparable, but still want to compare
doesnt really apply here though
you dont want Food to act as a Comparator
you want it to be comparable
it doesnt handle comparing. instead, it can be compared
"Food is Comparable"
vs "Food is a Comparator"
the T stuff is generics btw
so yeah, theres a lot ๐ฌ
Oh I get now , Food is Comparable , so the one getting compared is comparable , one comparing is comparator
Therefore the class need comparable , to actually compare something
Now onto Equals and Hashcode
yeah, the thing you want to be compared should be comparable
when you say it like that, seems obvious. its the code stuff that makes it seem complex
thats why understanding theory is important
When we are overriding an equals method in class , do I need to override haschode as well?
so basically what I am asking is will this code run?
import java.util.*;
class Food implements Comparable<Food> {
String name;
Integer quantity;
public Food(String name, Integer quantity){
this.name = name;
this.quantity = quantity;
}
@Override
public int compareTo(Food o) {
return name.compareTo(o.name);
}
@Override
public boolean equals(Object obj){
if(obj instanceof Food){
String otherName = ((Food) obj).name;
return name.equals(otherName);
}
return false;
}
}
public class ComparatorVsComparable {
public static void main(String[] args) {
List<Food> foodList = Arrays.asList(new Food("Mango",10),new Food("Apple",5),new Food("Guava",15));
Collections.sort(foodList);
for(Food food : foodList) System.out.println("Name : " + food.name + " Quantity : " + food.quantity);
}
}
need is one thing. you should
its more the other way around
in the end, you should always define both, unless the default behavior works for you
Well for this class I only need to compare Food name
I want to know how to implement hashcode
Do I need to create a hashing algorithm?
nope, could use Objects.hash for most cases
gotta understand why hashcode even matters
there are some data structures that make use of hashes
I asked this question but I can't seem to find my thread , any way to find one?
HashSet, HashMap
what thread?
I asked this question , what is the use of hashcode
oh, in #1051826284008853505 ?
yes
yeah i am just being dumb , let me go through that thread
okay so from my understand , hashing is a technique to retrieve an object in O(1) in best case
we use hashing algorithm and to help identify objects that belong to that hashcode
When 2 objects have same hashcode , it doesn't neccesary means they are equal and when we try to put objects in an array , based on there hashcode we might encounter an issue called as Collisions
Is that all?
Hey another thing , is the stream used in Stream API and Streams used in Files the same?
yeah, basically
its possible for 2 different objects to have the same hashcode
should be rare, if the hashcode is optimized
hash structures use "buckets" to store things. hashcode determines which bucket
if 2 different objects are stored in the same bucket, we need to use equals to finialize things, to make sure we get the right one
"FB" and "Ea" both have the same hashcode, even though they are different strings
thats why you should always implement both hashCode and equals
an InputStream is different from the Stream API
two different things
the Stream API is used to create sequences of actions to perform on a collection
if you had a List<String>, and wanted to get the length of all the non-null strings
you could filter for non-null, then map to String#length
List<Integer> lengths = list.stream()
.filter(str -> str != null)
.map(str -> str.length)
.toList();```
Yes but what does Stream<Integer> stream = List.of(1,2,3,4).toStream() means?
More specifically , what is Stream here?
its an object which is composed of actions to be performed
so you could do java stream .filter(...) .map(...)
specify the actions you want to perform on the collection
keep in mind, this doesnt actually modify the collection itself
A sequence of elements supporting sequential and parallel aggregate operations.
I thought Stream was a temporary collection which is consumed after one use
from the JavaDoc
its not a collection itself
i mean, in a sense, its a collection of operations
a sequence of operations
it doesnt contain the data that the list contains. a stream contains actions to be performed on the list
such as filtering
declaration: module: java.base, package: java.util.stream, interface: Stream
you need to practice this stuff to properly retain the info
this is a lot to take in, you might forget a lot
Well , let's see , I am tired
filter , map , reduce should be obvious , filter to remove particular elements , map to map on each element , reduce to reduce elements of list a particular list
we did cover those , I will most probably remember them , although I wouldn't be able to explain in a lot of detail as I usually do
if that works for you, whats next?
What's next is I am tired and I need a rest , I can't push further cause I am feeling hella sleepy
Thank you so much anyways
gnight, wish you the best of luck
it's morning here , 7:42 , I am awake all night preparing for interview and it's a in a few hours
but thanks
I really need that luck
@slim sable
Your question has been closed due to inactivity.
If it was not resolved yet, feel free to just post a message below
to reopen it, or create a new thread.
Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.
When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.
Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.
With enough info, someone knows the answer for sure ๐