Do both these classes support encapsulation and …?

前端 未结 3 1506
长发绾君心
长发绾君心 2021-01-22 08:35
public class Normal {
   public string name;     // name is public

   public String getName() {
        return name ;
   }

   public  String setName(String newName) {
         


        
3条回答
  •  时光说笑
    2021-01-22 09:12

    1. Different is a better example of encapsulation than Normal, though with something that simple, the benefits aren't really noticeable.

    2. Different is theoretically easier to maintain, because if you want to change the internal representation of name, you can without modifying the public API.

    3. Same as #2, for the same reasons.

    4. While the first class allows users to directly modify name, the second makes them go through getName() and setName().

    5. 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.

提交回复
热议问题