Skip to content
Sign upLog in
← Back to Community

can someone pls explain gets and sets in java?

Profile icon
MatthewXia

i learned this with trouble. would be glad if someone could help pls

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
MatthewXia
Comments
hotnewtop
Profile icon
Coder100

They are optional and will just help readability. For example:

class Human { private final String name; Human(String name) { this.name = name; } get String getName() { return name; } }

now you can use .getName() to get the name of a human in question.

Profile icon
MatthewXia

@Coder100
so wheres the sets and gets on the code?

Profile icon
Coder100

on line 4

@MatthewXia

Profile icon
MatthewXia

@Coder100
whats so special about that line?

Profile icon
MatthewXia

@Coder100
like how does a set and a get make it easier to read

Profile icon
Coder100

well, there is that get keyword which is what you are asking

@MatthewXia

Profile icon
MatthewXia

@Coder100
what about set

Profile icon
Coder100

set is just like setting a variable:

set variable(String newvalue) { this.var = newvalue; }

@MatthewXia

Profile icon
MatthewXia

@Coder100
so how does the set make it easier? if I may ask

Profile icon
Coder100

well, that's based on user preference

@MatthewXia

Profile icon
MatthewXia

@Coder100
so then whats the difference?

Profile icon
Coder100
Profile icon
Coder100

whatever you choose, in the end, they really are only for code readability, like comments

@MatthewXia

Profile icon
Coder100

Hi, they are basically sugar.

Profile icon
MatthewXia
Profile icon
MatthewXia

@Coder100
wdym by sugar

Profile icon
Coder100

as in features that make the user coding more easier, but can be accomplished regardless of its existence

@MatthewXia

Profile icon
MatthewXia

@Coder100
oh thx