The big idea: Defining a class writes the template. Instantiating creates an actual object from it.
The class is written once; objects are created as often as you need them.
The big idea: Defining a class writes the template. Instantiating creates an actual object from it.
The class is written once; objects are created as often as you need them.
class Book:
def __init__(self, title, author): # the CONSTRUCTOR
self.title = title # set this object's attributes
self.author = author
self.onLoan = False # a sensible starting state
def borrow(self):
if self.onLoan:
return False
self.onLoan = True
return True
b1 = Book("Dune", "Herbert") # instantiation
print(b1.borrow()) # True
print(b1.borrow()) # False — already outclass Book {
String title;
String author;
boolean onLoan;
Book(String title, String author) { // the CONSTRUCTOR
this.title = title; // set this object's fields
this.author = author;
this.onLoan = false; // a sensible starting state
}
boolean borrow() {
if (this.onLoan) {
return false;
}
this.onLoan = true;
return true;
}
}
Book b1 = new Book("Dune", "Herbert"); // instantiation
System.out.println(b1.borrow()); // true
System.out.println(b1.borrow()); // false — already outA class and its objects in memory: The class is stored once and holds only class-level (static) data. Each object gets its own block of memory on the heap for its instance variables: 20 Car objects means 20 blocks, one class.
A variable such as b1 holds a reference (the object's address), not the object itself.
Free preview
This is the free notes preview
You're reading the free notes. Aimnova Pro unlocks the full study experience — and you can try it with your first topic free to keep:
- FlashcardsLock in vocabulary and key terms with spaced repetition.
- Practice questionsAnswer exam-style questions and get instant AI marking.
- Mock exams & past-paper vaultSit full mocks and see exactly how examiners award marks.
- Personalised study planA daily plan built around your exam date and weak areas.
It runs automatically
- Called when the object is created, never by you directly
- Python names it __init__; Java names it after the class
- Whatever you pass at creation arrives as its parameters
It sets the starting state
- Gives every attribute a value before anything can use it
- So no object ever exists in an unfinished state
- onLoan starts False — a new book is not on loan
It can refuse
- Checks can be made before the object exists
- An empty title can be rejected at creation
- Far better than allowing a broken object and hoping
What self means: self is the object the method was called on.
self.title is this book's title; another object's method call has a different self. It is what lets one method definition serve every object.
What self means: this is the object the method was called on.
this.title is this book's title; another object's method call has a different this. It is what lets one method definition serve every object.
Not every attribute is a parameter: title and author come from outside, because they differ per book.
onLoan is set inside to a sensible default — a new book is never on loan, so asking the caller would be pointless and error-prone.
See how examiners mark answers
Answer exam-style questions with model answers. Learn exactly what earns marks and what doesn't.
library = [
Book("Dune", "Herbert"),
Book("Emma", "Austen"),
]
library.append(Book("Hamlet", "Shakespeare"))
for book in library: # objects go in lists like anything else
if book.borrow():
print("Borrowed:", book.title)
else:
print("Unavailable:", book.title)ArrayList<Book> library = new ArrayList<>();
library.add(new Book("Dune", "Herbert"));
library.add(new Book("Emma", "Austen"));
library.add(new Book("Hamlet", "Shakespeare"));
for (Book book : library) { // objects go in lists like anything else
if (book.borrow()) {
System.out.println("Borrowed: " + book.title);
} else {
System.out.println("Unavailable: " + book.title);
}
}Every method takes self
It is how the method knows which object it is working on.
You do not pass it: writing b1.borrow() supplies b1 as self automatically.
Methods return, rather than print
borrow() returns True or False, so the caller decides what to say about it.
A method that printed instead could not be used in an if statement, and could not be tested.
Objects behave like any value
They go in lists, get passed to functions, and are returned from them.
That is what makes a list of Book objects as easy to loop over as a list of numbers.
Every method has a this
It is how the method knows which object it is working on.
You do not pass it: writing b1.borrow() supplies b1 as this automatically.
Methods return, rather than print
borrow() returns True or False, so the caller decides what to say about it.
A method that printed instead could not be used in an if statement, and could not be tested.
Objects behave like any value
They go in lists, get passed to functions, and are returned from them.
That is what makes a list of Book objects as easy to loop over as a list of numbers.
Many objects in one array. Papers often store objects in an array and reach each one by its index.
shelf = [None] * 3 # room for 3 Book objects
shelf[0] = Book('Dune', 'Herbert')
shelf[1] = Book('Emma', 'Austen')
print(shelf[1].title) # Emma: index first, then the dot
count = 2 # how many places are filledBook[] shelf = new Book[3]; // room for 3 Book objects, all null at first
shelf[0] = new Book("Dune", "Herbert");
shelf[1] = new Book("Emma", "Austen");
System.out.println(shelf[1].getTitle()); // Emma: index first, then the dot
int count = 2; // how many places are filled- Default constructor
- A constructor with no parameters that gives every attribute a sensible starting value, so an object can be created before its details are known.
- Reference
- A variable holding an object stores where the object is, not a copy of it: two variables can refer to the same object.
Java, briefly: Java names the constructor after the class — public Book(String title) — and writes this.title where Python writes self.title.
The structure and the reasoning are the same; only the spelling differs.
toString() and __str__(): toString() in Java, or __str__() in Python, returns the object's attribute values as one readable string.
One call prints the whole object, which beats calling every accessor, and it is handy when debugging.
How this is tested — you must write a constructor that sets every attribute, and methods that return. It comes up two ways:
Paper 2 — working with code
- Construct a class with a constructor and methods, 4-6 marks
- Create objects and call their methods
- Explain what the constructor does
Paper 2 — the algorithmic-thinking question
- Explain the role of a constructor with no code shown
- Say why an attribute has a default rather than a parameter
The classic trap: Forgetting to set an attribute in the constructor. An object then exists with a missing value, and the failure appears much later — somewhere that has nothing to do with the cause.
Write a Student class holding a name and a list of marks, with a method to add a mark and one to return the average. Create two students and use both methods.
Model answer plan
See the answer broken into clear points, with guidance on how each point earns marks.
Write a Student class holding a name and a list of marks, with a method to add a mark and one to return the average. Create two students and use both methods.
Model answer plan
See the answer broken into clear points, with guidance on how each point earns marks.