Unit 3 · Classes and Objects · 10 min
Classes and objects
A class is a blueprint that describes what data an object holds and what it can do. An object is a real thing created from that blueprint.
Why this matters
This is the single most important idea in OOP. Everything else — inheritance, polymorphism, abstraction — sits on top of it.
Real-life analogy
A class is the architect's plan of a house. An object is an actual built house. One plan, many houses, each with its own colour and address.
Syntax
Syntax
class ClassName {
dataType field; // state
returnType method() { } // behaviour
}
ClassName obj = new ClassName();Example
Java
class Student {
String name;
int rollNumber;
void display() {
System.out.println(rollNumber + " - " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Ananya Rao";
s1.rollNumber = 12;
Student s2 = new Student();
s2.name = "Arjun";
s2.rollNumber = 15;
s1.display();
s2.display();
}
}Output
12 - Ananya Rao 15 - Arjun
Step by step
- 1`class Student` defines a new type with two fields and one method.
- 2`new Student()` asks the JVM for memory and builds one object.
- 3`s1` is a reference variable that points to that object.
- 4`s1.name = "Ananya Rao";` sets the field of that particular object.
- 5s1 and s2 are separate objects, each with its own copy of the fields.
- 6`s1.display()` runs the method using s1's data.
Key points
- Class = blueprint, object = instance of that blueprint
- Fields hold state, methods define behaviour
- new creates the object in memory
- Each object has its own copy of instance fields
Common mistakes
- Forgetting `new` and getting a NullPointerException
- Thinking a class occupies memory by itself — objects do
- Putting two public classes in one file
Try it yourself
- Create a Book class with title, author and price, then print two books.
- Add a method to Student that prints whether the student passed.