Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Image Added

Classes are one of the most important programming constructs in many programming languages. They are the , allowing us to use the object-oriented paradigm to organise code and make it more understandable. Classes are an abstract model or blueprint for an object. An object, like in the real world, can literally be anything, and all objects have properties and functions. And, like the real world, our code can consist almost entirely of interacting objects.

We can also understand classes as extended data types. Unlike the primitive data types we have already looked at, classes define both variables and functions. Programmers call class variables attributes and class functions function methods, but otherwise, they work pretty much the same as the variables and functions we already know. In order to To get access to these attributes and methods, we need to use a dot syntax, i.e. "." must be placed after the object name, followed by the name of the attribute or the method.

The structure of a class:

class className {

[Attributes - Variables]
[Constructor – Initialising function]

[Methods- Functions]

}

...

. For example car.speed might store the speed attribute of an object and the car.drive() method might be a method for moving the car around the screen.

Constructor

The constructor is the initialisation function of a class. This function is called when a new instance (a new object) of a class is created.

An object is created with the command 'new' and the subsequent call to the constructor. 

Attribute

Attributes are the variables of a class.

Methods

Methods are the functions of a class.

The basic principle of a class can be understood and used fairly quickly, and in some regards it Object Oriented Coding lends itself to a more Intuitive understanding of code. However, there is a lot of nuance and theory to writing a good class and it takes considerable practice.

Example BallClass

Below the draw function, you will find the BouncingBall class. It’s common practice to separate classes into their own file, to help keep code organised.

...

  • Modify the program so that many new balls are placed on the screen. Using an array and a for loop, it’s possible to quickly add hundreds balls!

Child classes - Keyword 'extends'

...

Polymorphism

...

Object-Oriented Coding (using classes to organise code) provides a number of powerful ways to use classes and objects. One more advanced feature is inheritance, where a class can be based on an existing class. This new class inherits the methods and attributes of the base class. However, if new methods or attributes in the child class have the same names as those in the base class, the base class properties are overwritten. To call reference the constructor of a base class from a child class, the keyword 'super' is used.

...