Chapter 58 - Use of Object-Oriented Programming (OOP) Flashcards
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) attempts to capture data, information and related functionality (code) to form structured items known as objects.
In OOP, the world is viewed as a collection of objects.
What are objects and what can they be.
Objects are instances of classes (defined in the main body). They can be anything: from specific things such as cars and planes, to more abstract things such as bank accounts or data structures (stacks).
Object features
Objects have their own attributes, states and methods (behaviours)
Attributes
Attributes are variables or data members that belong to a class and represent its characteristics or state
State
A state of an object is represented by its attributes e.g the radio is on/off
Methods/Behaviours
Actions performed by an object (think of them like subroutines) often by altering attributes.
What is a class?
A class is a blueprint/template for an object and it defines the attributes and behaviours (methods) of objects in that class.
These attributes are defined as the instance variables within a class.
Sections of a class
- Name of the class
- The attributes: all the information shared with any object of this class type. Like variables.
- The methods/behaviours: the code associated with the class that allows you to change/access its attributes. Like subroutines
Information hiding
As a general rule, attributes/instance variables are defined as private whereas most methods are defined as public. This allows other classes to access the methods but not see/change the attributes.
Therefore objects need to use messages to interact with with another object’s state.
What is a constructor?
What does the spec say about constructors?
A constructor initialises the attributes within a class.
Constructors are procedures with the name new. E.g def __init__ new (someAttributes).
Instantation
An instance of a class - the creation of an object
They have the name new when object is created. E.g my_dog = new Dog(someArguments)
Access the attribute “name” from the object my_dog. Then print it
print(my_dog.name)
Make the dog bark using the “bark” method. Then print
print(my_dog.bark())
Messages
Messages can either be getter or setter messages. In some languages, getter messages are written as functions (returning the value you wanted to get) wheras setter messages are written as procedures (usually used to change the state of the object).
Summary of OOP
Each object belongs to a class
All objects of the same class have the same structure and methods but they have their own data
Objects belonging to a class are instances of that class.