public class Normal {
public string name; // name is public
public String getName() {
return name ;
}
public String setName(String newName) {
Different
is a better example of encapsulation than Normal
, though with something that simple, the benefits aren't really noticeable.
Different
is theoretically easier to maintain, because if you want to change the internal representation of name
, you can without modifying the public API.
Same as #2, for the same reasons.
While the first class allows users to directly modify name
, the second makes them go through getName()
and setName()
.
If something is unencapsulated, you're exposing all the nitty gritty inner details to the world. This is difficult, if not impossible, to retroactively change, because you'll break any existing code that uses it.