Access Specifiers

The access specifiers define the level of visibility of a class’s members to other objects.

 

The following keywords are used to define the level of access:

  • public
    • public members are accessible any place the object is visible
    • public methods should be the only way to change an object’s attributes
    • public members make up an object’s public interface
  • private
    • private members are accessible only from other members of the same class
      • i.e. once instantiated, only that object
  • protected
    • protected members are accessible from other members of the same class and to members of derived classes derived
      • i.e. a child class can also access the protected members of the parent

The access specifier is declared within a class’s codeblock after its opening curly brace { by using one of the above keywords followed with a colon : All members following from that point forward are then considered to fall within the access specifier defined, up to the next access specifier or closing curly brace }

 

The default access specifier for a class is private, and can be omitted -- however, it’s good programming practice to include for the sake of readability (if only for yourself at a future stage).

 

The general rule is to keep all of your data private and provide public methods to access it. This concept is known as data hiding.

 

public:

With all members defined public, an object’s data can be changed without having to use its methods:

 

Compile & Run:

myTriangle width was set at 12
myTriangle height was set at 10
myTriangle area: 60

 

 

Although the method was called on line 28 to set the height for myTriangle, it was possible to directly access the height on line 29 since all members (including the object’s data on lines 7 and 8) are public.

 

 

private:

Now (correctly) defining the class’s data as private, we can only access its data by using its methods:

Compile & Run:

myTriangle width was set at 12
myTriangle height was set at 2000
myTriangle area: 12000

 

 

Since the default access specifier level for a class is private, any member not explicitly defined within an access specifier is assumed private.

 

 

protected: 

Allows derived/child class access:

Compile & Run:

myTriangle width was set at 12
myTriangle height was set at 2000
myTriangle area: 12000

 

In this overly simplified example, the height attribute for the child Triangle class is derived from the parent Shape class in which the child is inheriting the protected height data attribute.

Leave a Reply