Getters and Setters Flashcards

1
Q

What are getters and setters? What problem do they solve?

A

As a general rule, fields should start private, even when there’s no clear way to put them in an invalid state. To access a field for reading and writing, it’s Java convention to add getter and setter methods.

A getter returns the value of a field and, by convention, is named after the field prefixed by the verb get.

A setter accepts a value of the same data type as the field and assigns it to the field if it’s valid. By convention, it’s named after the field prefixed by the verb set.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Are getters and setters different from other methods? If so, how?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do I make a class variable read-only from outside an object?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do I make a class variable read-only from inside an object?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a computed getter? Give an example.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Where can I assign a default value to a class variable when an object is created?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How would you respond to the complaint: “Getters and setters are such a pain. It’s so much repetitive code!”

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly