nus-cs2113-AY2122S2 / forum

3 stars 2 forks source link

Situations where variables in a class can be public. #25

Closed siewyangzhi closed 2 years ago

siewyangzhi commented 2 years ago

Hi professor, I would like to enquire what are the scenarios whereby variables within a class can be public instead of private as so far, I have only seen private variables within a class and never public.

okkhoy commented 2 years ago

In general, you should always start with private for instance variables. In addition to good encapsulation, you can also do things like validation and stuff when you hide the variable and allow access using getter/setter. There may be situations where for convenience you use public, but it is not recommended.

siewyangzhi commented 2 years ago

I see thank you.