Class & Object in Java
Classes and objects are the heart of Java. A class is a blueprint that defines properties (fields) and behaviors (methods). An object is a concrete instance of a class, with its own state. Understanding classes and objects unlocks all of object-oriented programming.
Key Features
Blueprint
Class describes structure; object is an instance.
Fields & Methods
Data + behavior live together.
new Keyword
Allocates a new object on the heap.
this
Refers to the current object inside methods.
Modifiers
public, private, protected control access.
Reusable
One class can create unlimited objects.
Syntax
- Declare a class: class ClassName { fields; methods; }
- Create object: ClassName obj = new ClassName();
- Access field: obj.field
- Call method: obj.method()
Class Members
| Member | Description | Example | Note |
|---|---|---|---|
| Field | State / data | int age; | Instance var |
| Method | Behavior | void show() {} | |
| Constructor | Init code | ClassName() {} | Runs on new |
| Static | Class-level | static int count; | Shared across all objects |
Detailed Explanation & First Example
Let's start with a hands-on example. The program below shows the core idea behind Class and Object in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.
class Student
{
String name;
int age;
void show()
{
System.out.println(name + " : " + age);
}
}
class Main
{
public static void main(String args[])
{
Student s = new Student();
s.name = "Aman";
s.age = 21;
s.show();
}
}
Examples — Beginner to Advanced
The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.
class Book
{
String title;
double price;
Book(String t, double p) { title = t; price = p; }
void print() { System.out.println(title + " - " + price); }
}
class Main
{
public static void main(String args[])
{
Book b = new Book("Java Basics", 299.0);
b.print();
}
}
class Car
{
String model;
int year;
Car(String m, int y) { model = m; year = y; }
void show() { System.out.println(model + " (" + year + ")"); }
}
class Main
{
public static void main(String args[])
{
Car a = new Car("Swift", 2022);
Car b = new Car("Civic", 2024);
a.show();
b.show();
}
}
Civic (2024)
class Person
{
String name;
int age;
Person(String name, int age)
{
this.name = name;
this.age = age;
}
void show() { System.out.println(name + " " + age); }
}
class Main
{
public static void main(String args[])
{
new Person("Riya", 23).show();
}
}
class Counter
{
static int count = 0;
Counter() { count++; }
}
class Main
{
public static void main(String args[])
{
new Counter(); new Counter(); new Counter();
System.out.println("Total = " + Counter.count);
}
}
Notes & Tips
- Class names follow PascalCase: Student, BankAccount.
- Always initialize fields — Java assigns defaults (0, null, false) if not.
- Use this to disambiguate field vs parameter with same name.
- An object lives on the heap; its reference is on the stack.
- When no references remain, the garbage collector reclaims the object.
Real-World Use Cases
Domain Models
BankAccount, Customer, Transaction classes.
Game Entities
Player, Enemy, PowerUp objects.
Library Systems
Book, Member, Loan classes.
E-commerce
Product, Cart, Order classes.
Practice Questions
Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.
- Q1. Create a Rectangle class with length, breadth and area method.
- Q2. Create a Student class with marks of three subjects and an average method.
- Q3. Design a BankAccount class with deposit and withdraw methods.
- Q4. Add a static counter that tracks how many objects of a class have been created.
- Q5. Build a Library class containing an array of Book objects.
Interview Questions
These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.
A blueprint that defines fields and methods that its objects will have.
An instance of a class with its own copy of instance fields.
Class is a definition; object is a concrete runtime instance with state.
new do?Allocates memory on the heap, runs the constructor, and returns a reference to the new object.
this keyword?A reference to the current object; resolves naming conflicts with parameters.
FAQ
Unlimited — only memory limits the count.
On the heap; references live on the stack.
Yes — utility classes often have only static methods.
Yes — but it would just be a record-like data holder; consider using
record.
Yes — Java is case sensitive.
Common Mistakes to Avoid
Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Class and Object in Java:
- Forgetting the semicolon
;at the end of statements while using Class and Object. - Mixing up similar method names — read Java docs before using new APIs related to Class and Object.
- Ignoring compiler warnings — they often hint at bugs that will appear later in production.
- Hard-coding values that should come from configuration files or environment variables.
- Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
- Skipping unit tests — small tests prevent big regressions, especially around control flow.
At-a-Glance
Best Practices
Follow Conventions
Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.
Write Tests
Cover happy path and edge cases with JUnit before shipping changes to production.
Keep Methods Short
A method should do one thing and fit on a single screen. Refactor when it grows.
Validate Inputs
Never trust user input. Validate at the boundary, fail fast and log meaningfully.
Comment the Why
Comments should explain why a decision was made — not what the code does line by line.
Refactor Often
Small frequent refactors are cheap and safe; big rewrites are risky and expensive.
Pro Tips
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Class and Object | Class and Object concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
java.util, java.lang and java.io.
Summary
A class is the blueprint; an object is its real instance. Use fields for state, methods for behavior, and constructors to initialize. Master this duo and you've laid the foundation for all of Java's object-oriented power.