Class vs instance
Object-oriented programming (OOP) is a style of programming that models the world as objects. Each object has data (its attributes) and behavior (its methods).
A class is like a blueprint or cookie cutter. It defines what data and behavior every object of that type will have. An instance is one actual object created from the blueprint, with its own specific values.
Simple definition: A class is the recipe; an instance is the cake. You can bake many cakes from the same recipe, and each cake can have its own size and flavor.
Try it: Rectangle builder
Below is the same kind of tool that powers the CodeHS Java Class vs Instances PowerUp. Type a width and height, then click Create a new Rectangle to build an instance. Each instance keeps its own width and height, and you can call its methods.
Create a new Rectangle
public class Rectangle { private int width; private int height; public Rectangle(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } public int getArea() { return width * height; } public int getPerimeter() { return 2 * (width + height); } }
What the code means
- private int width, height; Each Rectangle object stores its own width and height.
privatemeans the values can only be read through methods, not directly. - public Rectangle(int width, int height) This is the constructor. It runs when you create a new Rectangle and copies the parameters into the object's variables.
- getWidth(), getHeight(), getArea(), getPerimeter() These methods are behaviors. They use the object's own data to return a result.
When you create two Rectangle instances, each one has its own copy of width and height. Calling getArea() on the first instance uses the first instance's data, and calling it on the second uses the second's data.
Why this matters
Classes and instances let programmers write code once and reuse it many times. You define the blueprint, then create as many objects as you need. This idea is behind everything from video game characters to bank accounts to user profiles.
Without classes, every rectangle in a program would need its own separate variables and functions. With classes, you write one Rectangle class and create dozens of Rectangle objects, each with its own width and height.
Quick quiz
1. What is a class in object-oriented programming?
2. What is an instance?
3. Why do two Rectangle instances have different areas?
Keep exploring programming
Now that you see how a class becomes an object, you can learn about inheritance, lists of objects, and how to design your own classes.
Part of the Programming Concepts tutorial series.