Classes and Objects in Java – Explained with Examples
Classes and objects are the foundation of Java. A class is a blueprint that describes what data something has and what it can do. An object is a real thing built from that blueprint, with its own values. Every Java program you write is made of classes, and almost everything it works with at runtime is an object.
This tutorial explains how to write a class, create objects, use references, and choose between instance and static members, with runnable examples.
1. What Are Classes and Objects?
Think of a house plan and the houses built from it. The plan (class) says every house has rooms, a door and a colour. Each house (object) is real, has its own address and colour, and can be changed without affecting the others.
| Class | Object |
|---|---|
| A blueprint or template | An instance built from the blueprint |
Declared once with the class keyword | Created many times with new |
| Exists in the source code and as loaded metadata | Exists in heap memory while the program runs |
Example: Car | Examples: a red Tata, a white Honda |
Every object has:
- State: the values of its fields (colour, speed).
- Behaviour: what its methods do (accelerate, brake).
- Identity: it is a distinct object, even if another object has the same values.
2. Anatomy of a Class
[access modifier] class ClassName [extends Parent] [implements Interfaces] {
// fields (variables): the data
// constructors: how objects are initialised
// methods: the behaviour
// nested classes, initializer blocks (optional)
}
By convention, class names use PascalCase (BankAccount), and a public class must be saved in a file with the same name (BankAccount.java).
3. Creating a Class and Objects
Here a Car class defines fields, a constructor and methods. Two objects are created from it, and each keeps its own speed:
public class Car {
// Fields (state)
String brand;
String color;
int speed;
// Constructor: runs when an object is created
Car(String brand, String color) {
this.brand = brand;
this.color = color;
this.speed = 0;
}
// Methods (behaviour)
void accelerate(int amount) { speed += amount; }
void brake() { speed = 0; }
String describe() { return color + " " + brand + " at " + speed + " km/h"; }
public static void main(String[] args) {
Car car1 = new Car("Tata", "red"); // object 1
Car car2 = new Car("Honda", "white"); // object 2
car1.accelerate(60);
car2.accelerate(40);
car2.accelerate(30);
System.out.println(car1.describe());
System.out.println(car2.describe());
car1.brake();
System.out.println(car1.describe());
}
}
red Tata at 60 km/h white Honda at 70 km/h red Tata at 0 km/h
4. What Happens When You Write new?
The statement Car car1 = new Car("Tata", "red"); does several things:
- Declaration:
Car car1creates a reference variable that can point to aCar. - Allocation:
newreserves memory for a new object on the heap and sets all fields to default values (null,0,false). - Initialisation: the constructor runs and sets the fields.
- Assignment: the reference to the new object is stored in
car1.
The variable does not contain the object itself; it holds a reference (like an address) to the object.
5. Reference Variables
Because variables hold references, copying a variable copies the reference, not the object. Two variables can then point to the same object:
public class References {
static class Box { int value; Box(int v) { value = v; } }
public static void main(String[] args) {
Box a = new Box(10);
Box b = a; // b refers to the SAME object as a
b.value = 99;
System.out.println("a.value = " + a.value);
Box c = new Box(99); // a different object with the same data
System.out.println("a == b: " + (a == b));
System.out.println("a == c: " + (a == c));
Box d = null; // refers to no object
try {
System.out.println(d.value);
} catch (NullPointerException e) {
System.out.println("d is null: NullPointerException");
}
}
}
a.value = 99 a == b: true a == c: false d is null: NullPointerException
==on objects checks whether two references point to the same object.- To compare contents, a class overrides
equals()(records do this automatically). - A reference set to
nullpoints to nothing; using it throwsNullPointerException.
6. Fields, Methods and Constructors
| Member | Purpose | Example |
|---|---|---|
| Field (instance variable) | Stores an object's state | String color; |
| Method | Defines behaviour | void brake() { speed = 0; } |
| Constructor | Initialises a new object; same name as the class, no return type | Car(String brand, String color) { ... } |
| Static field/method | Belongs to the class, shared by all objects | static int created; |
The keyword this refers to the current object. It is used to tell a field (this.brand) apart from a parameter with the same name (brand). See Constructors in Java and Methods in Java for details.
7. Instance Members vs Static Members
Instance fields exist once per object; static fields exist once per class. Here a static counter tracks how many objects were created, while each object keeps its own id:
public class StaticVsInstance {
static int created = 0; // one copy shared by the whole class
final int id; // one copy per object
StaticVsInstance() {
created++;
id = created;
}
public static void main(String[] args) {
StaticVsInstance x = new StaticVsInstance();
StaticVsInstance y = new StaticVsInstance();
StaticVsInstance z = new StaticVsInstance();
System.out.println("x.id=" + x.id + ", y.id=" + y.id + ", z.id=" + z.id);
System.out.println("Objects created: " + StaticVsInstance.created);
}
}
x.id=1, y.id=2, z.id=3 Objects created: 3
Static methods can be called without creating an object (Math.max(3, 5)), but they cannot use instance fields directly, because there is no "current object". Learn more in static keyword in Java.
8. Ways to Create Objects
The new keyword is by far the most common, but there are other ways:
import java.util.List;
public class CreateObjects {
static class Point implements Cloneable {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
static Point origin() { return new Point(0, 0); } // factory method
@Override public Point clone() {
try { return (Point) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); }
}
@Override public String toString() { return "(" + x + ", " + y + ")"; }
}
public static void main(String[] args) throws Exception {
Point p1 = new Point(3, 4); // 1. new keyword
Point p2 = Point.origin(); // 2. factory method
Point p3 = p1.clone(); // 3. clone()
Point p4 = Point.class.getDeclaredConstructor(int.class, int.class)
.newInstance(7, 8); // 4. reflection
System.out.println(List.of(p1, p2, p3, p4));
System.out.println("p3 is a copy, not the same object: " + (p1 != p3));
}
}
[(3, 4), (0, 0), (3, 4), (7, 8)] p3 is a copy, not the same object: true
| Way | When it is used |
|---|---|
new | Everyday object creation. |
| Static factory method | Named creation, caching or returning subtypes, e.g. List.of(), LocalDate.now(). |
clone() | Copying an existing object (copy constructors are usually preferred). |
| Reflection | Frameworks that create objects of classes known only at runtime. |
| Deserialization | Rebuilding objects from bytes, JSON or XML. |
9. Records: Classes for Plain Data
Many classes simply hold data. Since Java 16, a record declares such a class in one line, generating the constructor, accessor methods, equals(), hashCode() and toString():
public class RecordDemo {
// A record: constructor, accessors, equals, hashCode and toString are generated
record Book(String title, String author, int pages) { }
public static void main(String[] args) {
Book b1 = new Book("Clean Code", "Robert C. Martin", 464);
Book b2 = new Book("Clean Code", "Robert C. Martin", 464);
System.out.println(b1);
System.out.println("title(): " + b1.title());
System.out.println("b1.equals(b2): " + b1.equals(b2));
}
}
Book[title=Clean Code, author=Robert C. Martin, pages=464] title(): Clean Code b1.equals(b2): true
Records are immutable: their fields are final and cannot be changed after creation.
10. Anonymous Objects
If you need an object only once, you can create it without storing the reference, for example new Car("Kia", "blue").describe();. The object becomes eligible for garbage collection right after the statement finishes.
11. Object Lifetime and Garbage Collection
An object lives on the heap as long as some reference can reach it. When no references remain, for example after car1 = null; or when a local variable goes out of scope, the garbage collector may reclaim its memory. You never delete objects manually in Java. See Garbage Collection in Java.
12. Best Practices
- Give each class one clear responsibility.
- Make fields
privateand expose behaviour through methods (encapsulation). - Use constructors to put objects into a valid state immediately.
- Prefer immutable objects (final fields, records) when possible.
- Override
equals(),hashCode()andtoString()for value-like classes. - Use meaningful names: nouns for classes, verbs for methods.
13. Summary
- A class is a blueprint with fields, constructors and methods; an object is an instance created with
new. - Variables hold references to objects;
==compares references,equals()compares content. - Instance members belong to each object; static members belong to the class.
- Objects can also be created by factory methods, cloning, reflection and deserialization.
- Records offer a compact way to write immutable data classes.
Related Tutorials
Reference: dev.java: Classes and Objects
Frequently Asked Questions (FAQ)
Q1. What is a class in Java?
A class is a blueprint that defines the fields (data) and methods (behaviour) that its objects will have. It is declared with the class keyword and is the basic building block of every Java program.
Q2. What is an object in Java?
An object is an instance of a class, created at runtime with new. It has its own state (field values), behaviour (methods) and identity, and it lives in heap memory.
Q3. What is the difference between a class and an object?
A class is a template written once in code; an object is a concrete instance created from it, and you can create many objects from one class. A class does not hold field values; each object holds its own.
Q4. How do you create an object in Java?
Usually with the new keyword followed by a constructor call: Car car = new Car("Tata", "red");. Factory methods, cloning, reflection and deserialization can also create objects.
Q5. Where are objects stored in memory?
Objects live on the heap. Variables that refer to them, if they are local variables, live on the stack and hold only a reference to the heap object.
Q6. What is a reference variable?
A variable of a class type. It does not contain the object itself but a reference to it. Assigning one reference variable to another makes both point to the same object.
Q7. What is the difference between == and equals() for objects?
== checks whether two references point to the same object. equals() checks whether two objects are logically equal, as defined by the class; by default it behaves like == unless overridden.
Q8. What are instance variables?
Fields declared in a class without static. Each object gets its own copy, initialised to a default value (0, false or null) unless set by the constructor or an initializer.
Q9. What is the difference between static and instance members?
Instance members belong to each object and need an object to be used. Static members belong to the class itself, are shared by all objects, and can be accessed with the class name.
Q10. Can a class exist without objects?
Yes. Utility classes such as Math contain only static members and are never instantiated. They usually have a private constructor to prevent object creation.
Q11. What is an anonymous object?
An object created without assigning it to a variable, for example new Car("Kia", "blue").describe();. It can be used only once in that expression.
Q12. What does the this keyword mean?
this refers to the current object. It is used to access fields hidden by parameters with the same name, to call another constructor (this(...)), or to pass the current object to another method.
Q13. How many objects can be created from one class?
As many as memory allows. Each new call creates a separate object with its own state.
Q14. What happens to an object when no variable refers to it?
It becomes unreachable and eligible for garbage collection. The JVM will reclaim its memory at some later point; you do not need to free it manually.
Q15. Can a Java file contain more than one class?
Yes, but at most one top-level class can be public, and it must match the file name. Additional classes in the file are package-private. Nested classes can be declared inside other classes.
Q16. What is a record in Java?
A special kind of class (Java 16+) for immutable data. Declaring record Point(int x, int y) {} generates a constructor, accessors x() and y(), equals(), hashCode() and toString().
Q17. What is the default value of an object reference?
null, for fields. Local variables have no default value and must be assigned before use, or the code does not compile.
Q18. What is the Object class?
java.lang.Object is the root of every class hierarchy. Every class extends it directly or indirectly, inheriting methods such as equals(), hashCode(), toString() and getClass(). See Object class in Java.
Q19. Is a class a data type?
Yes. Every class defines a reference type. You can declare variables, parameters and return values of that type, for example Car myCar;.
Q20. What is the difference between declaring and instantiating an object?
Declaring (Car c;) creates a reference variable with no object. Instantiating (c = new Car(...)) creates the object and stores its reference in the variable. Both are often done in one statement.