A class is a construct found in Object Oriented Programming. It is a way of grouping data, and the methods for interacting with that data in one place. It also exposes a public interface that can be used by other code to interact with the class.
Classes have to be instantiated. That is to say, at some point if you’ve defined a lovely class MyLovelyClass
, in order to use it you will have to make a call to new MyLovelyClass()
.
To repeat what every guide to classes I’ve ever read says: Classes can be thought of as blueprints for how to make something.
It will often but not always model a real world object. To make this clearer let’s take a look at an example, using TypeScript:
class Bag {
constructor() {
this.contents = [];
}
private contents: String[];
}
Here we’ve modelled a bag, which can have things in it, in the form of an array of strings. It’s a bit useless at the moment as we can’t actually put anything in it, because the contents
array is private, so can’t be accessed from outside the class. To clarify:
const bag = new Bag();
bag.contents.push('sweet-coding-book');
This will not work, as bag.contents is not available to us. One solution would be to set the contents array to public:
public contents: String[]
But this would be a bad thing for a number of reasons. Firstly, if at any point we decide we want contents to be a different data type. For example lets say we decide to store our items in a dictionary instead:
public contents: { [key: string]: string; };
Now, if we have existing code that does something like below:
const bag = new Bag();
bag.contents.push('sweet-coding-book');
It will need to be changed. This example is trivial, but in a big project, this could take a long time to refactor.
Alternatively, if we did something like below, we can change our implementation of storing things in the bag, and any existing code will still work:
class Bag {
constructor() {
this.contents = {};
}
private contents: { [key: string]: string; };
public addItem(item: String) {
this.contents[item] = item;
}
}
const bag = new Bag();
bag.addItem('super-sweet-coding-book');
This is a pretty contrived example, but things similar to this happen all the time when coding.
So there is a very simple example of a class, which hopefully gives a basic understanding of what a class is, and a few of the benefits it offers.