Encapsulation

Computer Science: OCR A Level, topic 2.4.11

Encapsulation

Encapsulation in object-oriented programming is a principle that concerns how data inside the class can be accessed or changed.

Setters and getters

Setters and getters

  • A setter is a special type of method that sets one of the attributes equal to a specific value.
  • A getter is a special type of method that obtains the value of one of the attributes of the object.
Encapsulation

Encapsulation

  • Each attribute can only be accessed or modified by methods that are set (encapsulated) when defining the class.
  • This is also known as 'information hiding'.
  • The use of these methods protects the data in the class instance from being tampered with.
Different instances

Different instances

  • An instance of a class should not be able to alter the data of another instance of the same class.
  • For example, if you have an instance of a car class called “car1”, its methods should not be able to alter the attributes of another instance of the car class that is also running.

Test yourself on Encapsulation

  • What term is used for the method that obtains the value of one of the attributes of the object?

  • An instance of a class can alter the data of another instance of the same class.
    True or false?

  • Which method in the code shown is a setter for the object car1?

  • Which method in the code shown is a getter for the object car1?

Practise this topic for free