#What is Encapsulation?

1 messages ยท Page 1 of 1 (latest)

slim sable
#

I was reading a definition of Encapsulation and it's says , hiding the state of the object and exposing it through it's method
But there is also another definition , combining data and method into a unit called class

So which one is correct

atomic pondBOT
#

<@&987246399047479336> please have a look, thanks.

slim sable
slim sable
# neon whale 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

neon whale
slim sable
slim sable
hollow locust
#

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

slim sable
hollow locust
#

if you have a baseball, a basketball, and a soccer ball, you can create an abstraction Ball which defines the similarities

slim sable
#

But the definition the book gave called hiding data that is not required to be shown

hollow locust
#

a sports player may need to view the object as a Football

#

but stores may only care to view it as a Ball

hollow locust
#

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

slim sable
#

@hollow locust I thought Arrays.sort() is abstraction

#

Hiding the implentation of sorting technique

hollow locust
#

thats what abstracts the different comparing techniques used with that sort

slim sable
drowsy sedge
slim sable
drowsy sedge
#

getters and setters are usually harmful for encapsulation becuase they just give access to the state

slim sable
#

I thought they are used explicitly so that we can access the state

drowsy sedge
drowsy sedge
#

and every detail about the class

slim sable
#

why is this so confusing

drowsy sedge
#

sometimes u need to give access to state other times you want to hide it

#

allways depends on the usecase

neon whale
slim sable
#

and would that be called encapsulation?

hollow locust
#

no, getters/setters do not provide proper encapsulation for OOP

slim sable
#

Can anyone point me to a good article I can read and clear all these doubts

hollow locust
#

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

slim sable
hollow locust
#

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

slim sable
#

so why we use getter setters?
I guess monkey see monkey do really hampered from deeply understanding these stuff

hollow locust
#

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

slim sable
#

Probably a bad time to learn all of this , just 4 hrs remaining for interview

hollow locust
#

should have asked sooner ๐Ÿคทโ€โ™‚๏ธ

hollow locust
#

think in terms of state & behavior

#

hide state, expose behavior

#

thats encapsulation

hollow locust
#

and an object's methods define it's behaviors

hollow locust
#

thats the summary

slim sable
#

I see , I guess I just never questioned it much cause everyone just said the same definitions around me

  1. Encapsulation - > Binding data and functions together
  2. Abstraction -> Hiding implementation details
  3. Inheritance -> Inheriting properties of parent class
  4. Polymorphism -> Many forms
hollow locust
#

not bindind data & functions, rather "hiding state"

#

otherwise, thats a decent simplification

slim sable
#

I will just say both definitions if I remember it that time

hollow locust
#

if they question you about OOP, yet dont understand OOP themselves, thats a red flag

slim sable
#

i have been unemployed for over 1.5 years , i don't wanna throw any opportunity

hollow locust
#

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

slim sable
#

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

hollow locust
#

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

slim sable
hollow locust
#

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

slim sable
#

I am just going with -> Generalizing Concrete details and give example of ball , fish etc..

hollow locust
#

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"

slim sable
#

abstraction is generalizing concrete concepts into abstract concepts ?

#

how about this?

hollow locust
#

idk, im not the interviewer ๐Ÿ˜‚

#

if i was, id be like "yeah this person doesnt really know"

slim sable
hollow locust
#

generalization is a good word. "simplifying how we view something" is another

slim sable
#

I am doomed

hollow locust
#

if you had a TV, you could simplify it to an "Electronic"

#

categorize it

slim sable
#

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

hollow locust
#

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

slim sable
#

True

hollow locust
#

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

slim sable
#

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

hollow locust
#

never heard of them

#

all i know is that they're based in India and have a pool table

slim sable
#

i am based in india too

hollow locust
#

focus more on the studies rn, time is ticking

slim sable
hollow locust
#

none of that is going to help you better understand these concepts

#

and time is ticking. gotta either practice, or ask questions

slim sable
hollow locust
#

nope

#

a comparator makes use of comparable

slim sable
#

From what i have praticed comparable is something that a class implements
Comparator is the external sorting

hollow locust
#

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?

hollow locust
# slim sable

but the interview question part also dives into hashcode

#

how long did you procrastinate? ๐Ÿ’€

#

cause this is a lot

slim sable
#

Dude i don't have concepts on my fingertips

hollow locust
#

because youre asking about the 4 pillars of OOP

#

but the image mentions DSA & hashcodes

#

collections

slim sable
hollow locust
#

march 2024

#

id assume theyd ask similar questions

#

DSA is a 101 topic for computer science

slim sable
#

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

hollow locust
#

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

slim sable
#

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

hollow locust
#

and if you're gonna be working on tech ima use, id hope you know the stuff ๐Ÿ˜‚

hollow locust
#

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.

slim sable
#

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

hollow locust
#

yup

#

you can use it for persistence, but theres a good reason why it isnt used for that (outlined in my SO post)

slim sable
#

I will read it , here is another one

#

How does compareTo figure how to sort something in ascending or descending order?

hollow locust
#

it returns -1, 0, or 1

#

0 is equal

#

this is where JavaDocs come in handy

slim sable
#

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

hollow locust
#

go down to compareTo

hollow locust
#

for integers, its pretty straight forward

slim sable
#

How many experience do you have in Java?

I am a fresher , that should be obvious

hollow locust
#

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.

hollow locust
#

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

slim sable
#

For number i think it's easy , I just use IDE , so Integer.compare helps

#

Thanks btw

hollow locust
#

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

slim sable
# hollow locust when it comes to things like `String`, its up to whoever designs the class

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?

hollow locust
slim sable
#

Yeah

hollow locust
#

found the answer yourself

#

thats a sign of a true dev

#

sometimes you gotta go to the whiteboard, test things out

slim sable
#

Okay , so I am tinkering with the code
Instead of comparable I am using comparator and it is giving an error

hollow locust
#

whats the error message?

slim sable
#

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))

hollow locust
#

whats the code lookin like?

#

just so everything is on the table before explaining

slim sable
# hollow locust whats the code lookin like?

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

hollow locust
#

stick to the interview stuff first lmao

slim sable
#

So much for a fresher interview

hollow locust
#

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 ๐Ÿ˜ฌ

slim sable
#

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

hollow locust
#

when you say it like that, seems obvious. its the code stuff that makes it seem complex

#

thats why understanding theory is important

slim sable
#

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);
    }
}
hollow locust
#

its more the other way around

#

in the end, you should always define both, unless the default behavior works for you

slim sable
#

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?

hollow locust
#

nope, could use Objects.hash for most cases

#

gotta understand why hashcode even matters

#

there are some data structures that make use of hashes

slim sable
#

I asked this question but I can't seem to find my thread , any way to find one?

hollow locust
#

HashSet, HashMap

slim sable
hollow locust
#

oh, in #1051826284008853505 ?

slim sable
hollow locust
#

can just go to the searchbar and type "hashcode"

#

came up as the first for me

slim sable
#

yeah i am just being dumb , let me go through that thread

slim sable
# hollow locust `HashSet`, `HashMap`

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?

hollow locust
#

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

hollow locust
#

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();```
slim sable
#

Yes but what does Stream<Integer> stream = List.of(1,2,3,4).toStream() means?

#

More specifically , what is Stream here?

hollow locust
#

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.

slim sable
#

I thought Stream was a temporary collection which is consumed after one use

hollow locust
#

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

#

you need to practice this stuff to properly retain the info

#

this is a lot to take in, you might forget a lot

slim sable
#

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

hollow locust
#

what about encapsulation?

#

what about abstraction?

#

sort? Serializable?

slim sable
#

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

hollow locust
#

if that works for you, whats next?

slim sable
#

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

hollow locust
#

gnight, wish you the best of luck

slim sable
#

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

atomic pondBOT
#

@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 ๐Ÿ‘