Java Java Objects Harnessing the Power of Objects Constants

Why don't you change the MAX_PEZ variable from public final to private final?

Why don't you change the MAX_PEZ variable from public final to private final? Wouldn't it be the same, but harder to change?

2 Answers

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,735 Points

Hello Tianerad 999 .

Sorry, I have not watched the video but we have something we call Encapsulation in Java whereby we declare class variables as private (only accessible within the same class). This is to make sure that "sensitive" data is hidden from clients (users) using the variables.

For example, if MAX_PEZ variable was public then anyone or any class can make unauthorized changes to the value of MAX_PEZ resulting in a corrupted program. So making the variable private limits access to this variable to be within the class containing MAX_PEZ variable.

Try and imagine if an unauthorized class changes MAX_PEZ variable to 1,000,000.00, our program will be broken completely and won't function well.

Oh, that makes sense. Thanks for helping!