What is a class?
-
Classes are used as blueprints or templates that can be used to create objects within Object Oriented Programming or OOP
-
An object is created from a specific instance of a class and has its own state and behaviours
-
Using this method allows for reusable and organised code in a modular way
-
Consider a class of students
- Each student has a name, a date of birth and gender
-
Therefore we can create a blueprint or template for all students by making a class which contains these three attributes
-
As each student (or object) is created they will each have their own name, date of birth and gender attributes along with their own state for example
- Name “John”
- Date of birth “06/10/2015”
- Gender “Male”
-
Some classes are already prebuilt into a programming language saving the developer from having to write them from scratch and often provide common functionality
-
Examples from Java include:
- Date and calendar when working with dates
- String when working with strings of text
- Random when generating random numbers
- Scanner when reading input from a user or file
-
Custom classes are created by the programmer to define new data types
-
For example, a class for animals does not exist and so the programmer must define a custom class
-
Instantiation is the term used for creating an object from a class
-
Each class contains attributes which are essentially variables within a class and are also known as Class Variables
-
Objects that are created from a class contain attributes which are also known as instance variables
-
Classes can also contain methods/functions/procedures
-
Methods are actions or behaviours that can be performed
-
The name that is used to refer to an object is known as the identifier
-
Below is a visual representation of both a class and objects that have been instantiated
-
In the image below, the identifiers are P1 and P2
Example of a class and objects
Examiner Tips and Tricks
- Although you may see the terms methods/functions/ procedures, a method can be either a function or a procedure
- A function is a method that must return a value
- A procedure is a method that does not need to return a value
Worked Example
What is a class in object-oriented programming (OOP) ?
[2]
How to answer this question:
- Classes provide a way to organize code in a modular way [1]
- A blueprint or template for creating objects with specific attributes [1]
Answer:
Example answer to get full marks: A class is acts as a blueprint or template for creating objects with specific attributes [1 mark], while also providing a way to organize code in a modular fashion. [1 mark]