GCSE Link: None
In OOP, we usually have many different classes working together, each responsible for its own part of the program. Information hiding means that each class can keep its internal details (like helper methods) private, only exposing a clear, simple interface for other classes to use.
There are three levels of access restrictions that you can place on a method or attribute:
In C#, simply add the modifier (public
, protected
or private
) before the definition (for example
protected string Name =
"";
or public void
Output(...)
). By default, everything is private
.
You can even have different access modifiers for the get and set methods of an attribute.
For example, public string Name
{get; private set} = "";
can be read by any object (public
), but only written to from the same class
(private
).
Class definitions can be written to show the methods and attributes of a class.
The general format of a class definition is:
MyClass = Class
Public
Procedure Procedure1
Function Function1
Var1: Integer
Protected
Procedure Procedure2
Function Function2
Var2: String
Private
Procedure Procedure3
Function Function3
Var3: Boolean
End
Unless explicitly stated, all attributes (variables) should be private
,
with separate public
or protected
Get
and Set
methods if required.
A static method is one which can be used without instantiating the class that it is part of.
For example: the WriteLine()
method of the
Console
class (you don't need to instantiate a Console
object in order to use WriteLine()
). They can be
public
, protected
or
private
. In C#, the static
keyword is added
after the access modifier to mark a method as static.
A Player
class in a game has attributes
Name
, Health
and
XP
, all of which have public
getters and protected
setters. It also has an
Attack
procedure and Defend
method, both of which are private
, and a
public
TakeTurn
procedure.
Write the class definition for the
Player
class.
Player = Class
Public
Procedure TakeTurn
Function GetName
Function GetHealth
Function GetXP
Protected
Procedure SetName
Procedure SetHealth
Procedure SetXP
Private
Procedure Attack
Function Defend
Name: String
Health: Integer
XP: Integer
End