Class Definitions

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Declaration

A class should be declared, for any exam question you don't need to use a specific syntax or language:

NameOfClass = Class

or

Class NameOfClass

Sub Classes

If your class is a subclass then you need to specify which class it is based upon:

NameOfClass = Class (ParentClass)

or

NameOfClass = Class of ParentClass

or

Class NameOfClass = ParentClass

Private DataItems

It is normal to make all of the data items within a class private. This means they can't be accessed outside of the class itself, this could prevent any rogue updates of the data values. For each data item, the name and datatype should be specified:

NameOfClass = Class
   Private int DataItem1
   Private String DataItem2

Public Methods to Access DataItems

In order to access the data items, public methods should be created. This way you have more control over your data items and can provide a very specific to access or change your data:

NameOfClass = Class
   Private int DataItem1
   Public int GetDataItem1()
   { 
      Return DataItem1
   }
   Public int SetDataItem1(int Value)
   {
      DataItem1 = Value
   }

Static, Abstract, Virtual

Static

The "static" modifier means that a class cannot be instantiated, and the subroutines must instead be called directly.

Abstract

The "abstract" modifier when declaring a class means that the class contains one or more abstract subroutine, and must have one or more subclasses for implementations of abstract methods. A subclass of an abstract class that is instantiated must implement any abstract subroutines contained in the abstract class.

Virtual

A virtual method is one which is inheritable and can be overridden.

Constructors

A constructor method is run when the class is used to create an object (instantiation), but a constructor is not compulsory and a class can even have several constructors. A constructor is a method that uses the class name as the name for the method:

NameOfClass = Class
   Private int DataItem1
   Public int GetDataItem1()
   { 
      Return DataItem1
   }
   Public int SetDataItem1(int Value)
   {
      DataItem1 = Value
   }
   Public void NameOfClass()
   {
      DataItem1 = 0
   }