SLIDE 38 X Internet of Things 2019-2020 April 29, 2020
Encapsulation
- Suppose we need to change our Song class and
now the field artist should be named a
- The code using Song will break!
- Another problem is that since the fields are directly
accessible, they are writable even though we could wish to prevent such behaviors (read-only fields)
- This happens because the Song class was
exposing too many details about its implementation on the outside and other parts of the code were accessing the data directly
class Song { String a; String t; ... Song(String artist, String title) { this.a = artist; this.t = title; } }
Song.java
... Song song = new Song("Rammstein","Ich Will"); ... String artist = song.artist; ...
<someone else’s class>.java