Classes and Objects
A review of classes and objects in all five languages: a Snack class with fields, a constructor and methods, objects made from it, and the classic shape of a Java program you'll see in textbooks.
Apprentice · C# · Java · Python · JavaScript · TypeScript · Updated
After this lesson you can
- Write a class with fields, a constructor and a method
- Create objects from a class and call their methods
Key takeaways
- A class is a blueprint, like a form with blanks; an object is one filled-in copy of it.
- Fields hold an object's own data, a constructor fills them in when the object is made, and methods are the jobs the object can do.
- Every structure in this course, from a linked list to a graph, is written as a class.
Say the snack stand's program keeps its snacks in three lists side by side: one of names, one of prices, one of counts, so snack 2's price is prices[2]. Then the pretzels sell out, and someone removes "Pretzel" from the names list but forgets the other two. Now every snack after it has the wrong price and the wrong count, and nothing in the code says so. Three lists that must stay in step are three chances to fall out of step.
The fix is to keep each snack's facts together. The stand already does it on paper: an index card for each snack, with its name, its price, and how many are left. Every card has the same blanks; only what's written in them changes. In code, the blank card is a class, and each filled-in card is an object. Every structure in this course, a linked list, a hash table, a tree, is written as a class, so this lesson is worth getting comfortable with.
The blueprint and the copies
A class describes what every object of its kind has and can do:
- Fields are the blanks on the card:
name,price,count. Each object has its own. - A constructor is the code that runs when a new object is made. It fills in the fields from the values you pass it.
- Methods are the jobs an object can do with its own data, such as working out what its stock is worth, or selling a few.
An object is one copy made from the class. The pretzel card and the trail-mix card are two objects of the same class, Snack.
A Snack class
Snack pretzel = new Snack("Pretzel", 3, 12);
Snack trailMix = new Snack("Trail Mix", 4, 8);
Console.WriteLine(pretzel.Name + ": " + pretzel.Count + " left, worth quot; + pretzel.Value());
pretzel.Sell(5);
Console.WriteLine("After selling 5: " + pretzel.Count + " left");
Console.WriteLine(trailMix.Name + ": " + trailMix.Count + " left, worth quot; + trailMix.Value());
class Snack
{
public string Name;
public int Price;
public int Count;
public Snack(string name, int price, int count)
{
Name = name;
Price = price;
Count = count;
}
public int Value()
{
return Price * Count;
}
public void Sell(int amount)
{
Count -= amount;
}
}
Pretzel: 12 left, worth $36
After selling 5: 7 left
Trail Mix: 8 left, worth $32
class Snack {
String name;
int price;
int count;
Snack(String name, int price, int count) {
this.name = name;
this.price = price;
this.count = count;
}
int value() {
return price * count;
}
void sell(int amount) {
count -= amount;
}
}
void main() {
Snack pretzel = new Snack("Pretzel", 3, 12);
Snack trailMix = new Snack("Trail Mix", 4, 8);
IO.println(pretzel.name + ": " + pretzel.count + " left, worth quot; + pretzel.value());
pretzel.sell(5);
IO.println("After selling 5: " + pretzel.count + " left");
IO.println(trailMix.name + ": " + trailMix.count + " left, worth quot; + trailMix.value());
}
Pretzel: 12 left, worth $36
After selling 5: 7 left
Trail Mix: 8 left, worth $32
class Snack:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
def value(self):
return self.price * self.count
def sell(self, amount):
self.count -= amount
pretzel = Snack("Pretzel", 3, 12)
trail_mix = Snack("Trail Mix", 4, 8)
print(f"{pretzel.name}: {pretzel.count} left, worth ${pretzel.value()}")
pretzel.sell(5)
print(f"After selling 5: {pretzel.count} left")
print(f"{trail_mix.name}: {trail_mix.count} left, worth ${trail_mix.value()}")
Pretzel: 12 left, worth $36
After selling 5: 7 left
Trail Mix: 8 left, worth $32
class Snack {
constructor(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
value() {
return this.price * this.count;
}
sell(amount) {
this.count -= amount;
}
}
const pretzel = new Snack("Pretzel", 3, 12);
const trailMix = new Snack("Trail Mix", 4, 8);
console.log(`${pretzel.name}: ${pretzel.count} left, worth ${pretzel.value()}`);
pretzel.sell(5);
console.log(`After selling 5: ${pretzel.count} left`);
console.log(`${trailMix.name}: ${trailMix.count} left, worth ${trailMix.value()}`);
Pretzel: 12 left, worth $36
After selling 5: 7 left
Trail Mix: 8 left, worth $32
class Snack {
name: string;
price: number;
count: number;
constructor(name: string, price: number, count: number) {
this.name = name;
this.price = price;
this.count = count;
}
value(): number {
return this.price * this.count;
}
sell(amount: number): void {
this.count -= amount;
}
}
const pretzel = new Snack("Pretzel", 3, 12);
const trailMix = new Snack("Trail Mix", 4, 8);
console.log(`${pretzel.name}: ${pretzel.count} left, worth ${pretzel.value()}`);
pretzel.sell(5);
console.log(`After selling 5: ${pretzel.count} left`);
console.log(`${trailMix.name}: ${trailMix.count} left, worth ${trailMix.value()}`);
Pretzel: 12 left, worth $36
After selling 5: 7 left
Trail Mix: 8 left, worth $32
What to notice in each language:
- Making an object is
new Snack(...)in C#, Java, JavaScript and TypeScript, and plainSnack(...)in Python. - The constructor is a method with the class's own name in C# and Java,
constructorin JavaScript and TypeScript, and__init__(read "dunder init") in Python. - An object's own fields are reached with
this.in Java, JavaScript and TypeScript, and withself.in Python, where every method listsselfas its first parameter. C# lets you leavethis.out. - Selling 5 pretzels changed only the pretzel object. The trail mix kept its own count, because each object has its own fields.
The classic Java program
The Java tab above uses Java 25's short form: a file with a void main() and the class beside it. Many textbooks and AP classes still write every Java program in the classic shape below. It's the same program; the classic form wraps main in a class of its own, marks it public static, and prints with System.out.println:
public class Main {
public static void main(String[] args) {
Snack pretzel = new Snack("Pretzel", 3, 12);
System.out.println(pretzel.name + ": " + pretzel.count + " left, worth quot; + pretzel.value());
}
}
class Snack {
String name;
int price;
int count;
Snack(String name, int price, int count) {
this.name = name;
this.price = price;
this.count = count;
}
int value() {
return price * count;
}
}
Pretzel: 12 left, worth $36
Both run with java followed by the file name. When your class's code uses the classic form, everything in this course still applies; only the wrapper is different.
Try it. Add a third snack, "Apple Chips", at $2 with 15 left, and print what its stock is worth. Then add a method restock(amount) that adds to the count.
Check yourself
2 questions to try on the lesson page.
So what
From Module 2 on, every structure you build is a class: a LinkedList, a Stack, a HashTable, each with fields that hold its data and methods for its jobs. The pattern is always the one you just wrote for a snack.