Tuesday, September 22, 2015

Set and Get Methods vs. public Data

It would seem that providing set and get capabilities is essentially the same as making the

instance variables public. This is one of the subtleties that makes Java so desirable for software

engineering. A public instance variable can be read or written by any method that

has a reference to an object containing that variable.
 If an instance variable is declared private,

a public get method certainly allows other methods to access it, but the get method

can control how the client can access it. For example, a get method might control the format




of the data it returns and thus shield the client code from the actual data representation.

A public set method can—and should—carefully scrutinize attempts to modify the

variable’s value and throw an exception if necessary. For example, an attempt to set the day

of the month to 37 would be rejected, an attempt to set a person’s weight to a negative

value would be rejected, and so on. Thus, although set and get methods provide access to

private data, the access is restricted by the implementation of the methods. This helps



promote good software engineering...

1 comment:

  1. This was an interesting class . I am really enjoying these classes . xD

    ReplyDelete