Before an architect builds houses in a colony, they draw a plan: number of rooms, where the doors go, the size of the kitchen. From that one plan, fifty houses can be built. Each house is real, has its own address, its own paint colour and its own family living in it, but all of them follow the same plan.
In OOP the plan is a class and each house is an object. In this chapter we will learn exactly what classes and objects are, how to create them in Java, what happens in memory, how references work, and how C++ and Python handle the same ideas.
What Is a Class?
A class is a user-defined type that acts as a blueprint for objects. It declares the data (fields) every object of that type will hold and the operations (methods) those objects can perform.
A class usually contains:
Fields (also called attributes, instance variables or data members): the data.
Methods (member functions): the behaviour.
Constructors: special code that sets up a new object (next chapter, Constructors & Destructors).
A class is a logical entity. Writing a class does not create any student, car or account; it only describes what they will look like.
What Is an Object?
An object is an instance of a class: a concrete entity created at run time, occupying memory, with its own values for the fields declared by the class.
Every object has three characteristics:
Characteristic | Meaning | Example (a car object) |
|---|---|---|
State | Current values of its fields | brand = "Tata Nexon", colour = "Blue", speed = 60 |
Behaviour | What it can do (its methods) | accelerate(), brake(), show() |
Identity | What makes it a distinct object | Its own location in memory; two blue Nexons are still two cars |
Defining a Class and Creating Objects in Java
class Car {
// fields (state)
String brand;
String colour;
int speed;
// methods (behaviour)
void accelerate(int amount) {
speed += amount;
}
void brake() {
speed = 0;
}
void show() {
System.out.println(colour + " " + brand + " running at " + speed + " km/h");
}
}
class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Tata Nexon";
car1.colour = "Blue";
Car car2 = new Car();
car2.brand = "Maruti Swift";
car2.colour = "Red";
car1.accelerate(60);
car2.accelerate(40);
car2.accelerate(30);
car1.show();
car2.show();
car1.brake();
car1.show();
car2.show();
}
}Output:
Blue Tata Nexon running at 60 km/h
Red Maruti Swift running at 70 km/h
Blue Tata Nexon running at 0 km/h
Red Maruti Swift running at 70 km/hStep by step:
class Car { ... }defines the blueprint with three fields and three methods.new Car()creates an actualCarobject.car1andcar2are two separate objects.The dot operator (
car1.brand,car1.accelerate(60)) accesses a field or calls a method of that particular object.Inside a method, a field name like
speedmeans "the speed of the object this method was called on". Whencar1.brake()runs, onlycar1's speed becomes 0;car2keeps going at 70.
This last point is the most important: methods are written once in the class, but each call works on the state of one specific object.
In this chapter we assign fields directly (
car1.brand = ...) to keep things simple. Real classes use constructors to set initial values and keep fields private. We will fix both in Constructors & Destructors and Encapsulation.
What Exactly Does new Do?
The single line
Car car1 = new Car();actually does three separate things:
Part | Name | What happens |
|---|---|---|
| Declaration | Creates a reference variable that can point to a |
| Instantiation | Allocates memory for a new |
| Initialization | Calls the constructor to set up the object, then the address (reference) is stored in |
STACK (main's variables) HEAP (objects)
+-------------+ +--------------------------+
| car1 ref --+------------------> | Car |
+-------------+ | brand = "Tata Nexon" |
| car2 ref --+---------+ | colour = "Blue" |
+-------------+ | | speed = 0 |
| +--------------------------+
| +--------------------------+
+--------> | Car |
| brand = "Maruti Swift" |
| colour = "Red" |
| speed = 70 |
+--------------------------+So car1 is not the object; it is a reference (a kind of safe pointer) to the object. The full story of stack, heap and garbage collection is in Object Lifecycle & Memory.
Default Values of Fields
When new creates an object, Java fills every field with a default value before any of your code runs.
class Student {
String name;
int age;
double cgpa;
boolean hostel;
}
class Main {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name + " " + s.age + " " + s.cgpa + " " + s.hostel);
}
}Output:
null 0 0.0 falseField type | Default value |
|---|---|
|
|
|
|
|
|
|
|
Any reference type ( |
|
This applies only to fields. Local variables inside a method get no default value, and using one before assigning it is a compile-time error:
class Main {
public static void main(String[] args) {
int count;
System.out.println(count);
}
}Main.java:4: error: variable count might not have been initialized
System.out.println(count);
^
1 errorC++ is different: fields of built-in types like int are not automatically zeroed in many cases and may contain garbage, which is why C++ programmers always initialise them in constructors.
References, Aliasing and null
Because variables hold references, assigning one object variable to another does not copy the object.
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
}
class Main {
public static void main(String[] args) {
Student a = new Student("Ishaan", 80);
Student b = a; // copies the reference, not the object
Student c = new Student("Ishaan", 80); // a separate object with same values
b.marks = 95;
System.out.println("a.marks = " + a.marks);
System.out.println("a == b : " + (a == b));
System.out.println("a == c : " + (a == c));
Student d = null;
System.out.println(d.name); // no object to read from
}
}Output (compiled with javac -g so the error message shows variable names):
a.marks = 95
a == b : true
a == c : false
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "d" is null
at Main.main(Main.java:24) a ---+
+----> [ Student: "Ishaan", 95 ] b = a → same object (alias)
b ---+
c --------> [ Student: "Ishaan", 80 ] a different object
d --------> (nothing) nullStudent b = a;copies the reference. Nowaandbare two names for one object, so changingb.markschanges whatasees. This is called aliasing.==on objects compares identity (do both references point to the same object?), not content.a == cisfalseeven though both students were created with the same values. Comparing content is done withequals(), which a class must override to be meaningful.nullmeans "refers to no object". Using a field or method through anullreference throws aNullPointerExceptionat run time. Since Java 15 (helpful NullPointerExceptions), the message tells you exactly which variable was null.
If you actually need a separate copy of an object, you must create one yourself. How to do that correctly is the topic of Shallow Copy vs Deep Copy.
Does a Class Occupy Memory?
This is a common exam trap. Defining a class does not create any object, so no memory for instance fields is allocated just by defining a class. Memory for fields is allocated each time an object is created.
However, the class itself is not completely free: when a Java class is first used, the JVM loads its definition (method code, constant pool and static fields) into a memory area called the method area / Metaspace, once per class.
What | How many copies |
|---|---|
Instance fields ( | One per object |
Method code ( | One per class, shared by all objects |
Static fields | One per class (see Static vs Instance Members) |
So when you create 1,000 Car objects, you get 1,000 sets of fields but still only one copy of the code of accelerate().
Classes and Objects in C++
C++ gives you more control, and a couple of differences are frequently asked in interviews.
#include <iostream>
#include <string>
struct PointS { // members are public by default
int x, y;
};
class PointC { // members are private by default
int x, y;
public:
PointC(int x, int y) : x(x), y(y) {}
void print() const { std::cout << "(" << x << ", " << y << ")\n"; }
};
int main() {
PointS a{3, 4};
a.x = 10; // fine: public
std::cout << "(" << a.x << ", " << a.y << ")\n";
PointC b{3, 4}; // object on the stack, no 'new' needed
// b.x = 10; // error: 'int PointC::x' is private
b.print();
PointC* p = new PointC{7, 8}; // object on the heap
p->print();
delete p; // C++ has no garbage collector
}Output (g++ 15, -std=c++23):
(10, 4)
(3, 4)
(7, 8)If we uncomment b.x = 10;, compilation fails:
err.cpp: In function ‘int main()’:
err.cpp:21:7: error: ‘int PointC::x’ is private within this context
21 | b.x = 10; // error: 'int PointC::x' is private
| ^
err.cpp:9:9: note: declared private here
9 | int x, y;
| ^In C++,
structandclassare almost identical. The only difference is the default access:structmembers (and base classes) arepublicby default,classmembers areprivateby default.C++ objects can live directly on the stack (
PointC b{3, 4};) withoutnew. In Java, every object is created withnewand lives on the heap (conceptually).An object created with
newin C++ must be released withdelete, because C++ has no garbage collector. Modern C++ prefers smart pointers likestd::unique_ptrso that this happens automatically.When accessing members through a pointer, C++ uses
->(p->print()) instead of the dot.
Classes and Objects in Python
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def report(self):
return f"{self.name}: {self.marks}"
a = Student("Ishaan", 80)
b = Student("Diya", 92)
print(a.report())
print(b.report())
b.city = "Pune" # Python lets you add a new attribute to ONE object
print(b.city)
print(hasattr(a, "city"))
print(type(a).__name__, a is b)Output (Python 3.14):
Ishaan: 80
Diya: 92
Pune
False
Student FalsePython creates fields inside
__init__by assigning toself.name; there are no field declarations.selfis the Python equivalent of Java'sthis: the object the method was called on. It must be written explicitly as the first parameter.Python is dynamic: you can even add a new attribute to a single object (
b.city) at run time. Java and C++ do not allow this; the set of fields is fixed by the class.Python's
iscompares identity, like Java's==on objects.
Class vs Object
Class | Object |
|---|---|
Blueprint / template | Instance created from the blueprint |
Logical entity | Physical (run-time) entity in memory |
Declared once with the | Created as many times as needed, usually with |
No memory for instance fields when defined | Gets memory for its own fields when created |
Example: | Example: the blue Tata Nexon in |
Exists at compile time (and is loaded once at run time) | Exists only at run time, from creation until it is destroyed/collected |
How to Find Classes in a Problem Statement
In design rounds and UML exercises you are often given a paragraph and asked to identify classes. A simple and effective trick:
Nouns → candidate classes or fields.
Verbs → candidate methods.
Example: "A library has many books. A member can borrow a book for 14 days and return it. A late return creates a fine."
Class | Fields | Methods |
|---|---|---|
| isbn, title, author, available | markBorrowed(), markReturned() |
| memberId, name, borrowedBooks | borrow(book), returnBook(book) |
| book, member, issueDate, dueDate | isOverdue(), calculateFine() |
| books, members, loans | issue(book, member), accept(loan) |
"14 days" becomes a value (a constant or a field), not a class. Not every noun becomes a class; you keep the ones that have their own data and behaviour. The chapter UML Class Diagrams shows how to draw such designs.
Common Mistakes Students Make
Thinking the variable is the object. In Java,
car1holds a reference. Two variables can refer to the same object.Using
==to compare object contents.==checks identity. For strings and other objects, useequals().Forgetting to create the object.
Car c;followed byc.brake();does not compile for a local variable, and a field left asnullthrowsNullPointerException.Expecting
b = ato copy. It only copies the reference.Writing "a class occupies no memory at all". Precise answer: no memory for instance data until objects are created; the class's code and static data are loaded once.
Interview / GATE-Style Questions
1. What is the difference between a class and an object?
A class is a blueprint describing fields and methods; an object is a run-time instance of that class with its own field values and identity. One class can produce many objects.
2. How many objects are created by the following code? Car a = new Car(); Car b = a; Car c = new Car(); Car d;
Two. Only new creates objects. b is an alias of a's object, and d is just an uninitialised reference.
3. What does this print? Student a = new Student("X", 50); Student b = a; b.marks = 70; System.out.println(a.marks);
70. a and b refer to the same object, so the change through b is visible through a.
4. What is the difference between struct and class in C++?
Only the default access: struct members and inheritance are public by default; class members and inheritance are private by default. Both can have constructors, methods, inheritance and virtual functions.
5. If 100 objects of a class are created, how many copies of an instance method exist in memory?
One. Method code belongs to the class and is shared. Only instance fields are duplicated per object.
6. What are the default values of an int field, a boolean field and a String field in Java?
0, false and null. Local variables, however, get no default and must be assigned before use.
7. Can a class exist without any object being created from it?
Yes. For example, a utility class like Math is used only through static methods, and an abstract class can never be instantiated directly. A class is just a definition; creating objects is optional.
Summary
A class is a blueprint that declares fields and methods; an object is an instance with its own state, shared behaviour and unique identity.
newallocates an object, sets default field values and runs a constructor; the variable stores a reference to it.Fields get default values (
0,false,null); local variables do not.Assigning references creates aliases;
==compares identity; using anullreference throwsNullPointerException.Instance fields are per object; method code is shared per class.
C++
structvsclassdiffer only in default access; C++ objects can live on the stack. Python objects are dynamic and useself.
Next, in Constructors & Destructors, we will see how objects are properly initialised when they are born and cleaned up when they die.