15. Data encapsulation

One of the powerful properties of an OOP language is the idea of data encapsulation. This means that data within a class cannot normally be altered by any code outside the class. The data is 'encapsulated'.

Consider the now familiar Box example

class Box() {
private var width
private var height


  public function Box() {
    var myBox = new Box
  }


  public setHeight(x) {
    myBox.height = x
  }

}

Notice the line 'private var height'.

This is declaring that a variable called height exists within the class, but it will not be visible to any code outside the class. The only way it can be altered is for the main code to call the setHeight method of the class.

Data encapsulation make software more robust because it is much harder for faulty code to over-write data, unlike conventional procedural languages

 

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: Data encapsulation

 

 

Copyright © www.teach-ict.com