简体   繁体   中英

How to use encapsulation?

After I read online E-book.They said the benefit of encapsulation is "A class can change the data type of a field and users of the class do not need to change any of their code." . I don't understand what they say in the point. What is the main meaning of the point? Can you give an example,please?

Let's take a simple class Vehicles, which maintains a list:

public class Vehicles {

    private ArrayList<String> vehicleNames;

    Vehicles() {
        vehicleNames = new ArrayList<String>();
    }

    public void add(String vehicleName) {
        vehicleNames.add(vehicleName);
    }
}

This will be used by a client in the following way:

public class Client {

    Public static void main(String []args) {
        Vehicles vehicles = new Vehicles();
        vehicles.add("Toyota");
        vehicles.add("Mazda");
    }
}

Now if Vehicles changes its internal private vehicleNames field to be a LinkedList instead, Client would be unaffected. That is what the book is talking about, that the user/client does not need to make any changes to account for the changes in the class due to encapsulation.

Encapsulation is really important in Object-Oriented Programming. Using encapsulation, you can hide information from users who use your class library/API.

"And why do I need to hide stuff from the users?", you ask. There are a lot of reason. One main reason is that some users who are naughty or just don't know what the API is doing may mess with your classes and stuff. Let me give you an example.

Suppose you have a class here:

public class Computer {
    public int coreCount;
}

As you can see here, coreCount is declared public . That means all other classes can access it. Now imagine a naughty person do this:

Computer myPC = new Computer ();
myPC.coreCount = 0;

Even fools can tell that this doesn't make any sense. It might also affect your program's other stuff. Imagine you want to divide by the core count. An Exception would occur. So to prevent this, we should create setters and getters and mark the field private .

C# Version:

public class Computer {
    private int coreCount;
    public int CoreCount {
        get {return coreCount;}
        set {
            if (value > 0)
                coreCount = value;
        }
    }
}

Java version

public class Computer {
    private int coreCount;
    public int getCoreCount () {return coreCount;}
    public void setCoreCount (int value) {
        if (value > 0)
            coreCount = value;
}

Now no one can set the core count to non-positive values!

Here's an example of encapsulation. Say we have a Person class, like so

class Person {
  private String name;
  private String email;
  public String getName() { return this.name; }
  public String getEmail() { return this.email; }

  public void setName(String name) { this.name = name; }
  public void setEmail(String email) { this.email = email; }
}

And at some point, we decide we need to store these values not as a couple strings, but as a HashMap (for some reason or another).

We can change our internal representation without modifying the public interface of our Person class like so

class Person {
  HashMap<String, String> data;
  public Person() {
    this.data= new HashMap<String, String>();
  }
  public String getName() { return this.data.get("name"); }
  public String getEmail() { return this.data.get("email"); }

  public void setName(String name) { this.data.put("name", name); }
  public void setEmail(String email) { this.data.put("email", email); }
}

And from the client code perspective, we can still get and set Strings name and email without worrying about anything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM