Class and Object in Java Tutorial
Chapter 17 · Java Programming Series
PBA Institute 12 min read Beginner to Intermediate 2024

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

MemberDescriptionExampleNote
FieldState / dataint age;Instance var
MethodBehaviorvoid show() {}
ConstructorInit codeClassName() {}Runs on new
StaticClass-levelstatic 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.

Simple Class and Object
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();
    }
}
Output Aman : 21

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 with Constructor
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();
    }
}
Output Java Basics - 299.0
Multiple Objects
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();
    }
}
Output Swift (2022)
Civic (2024)
Using this
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();
    }
}
Output Riya 23
Static Field
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);
    }
}
Output Total = 3

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.

Q1 What is a class?
A blueprint that defines fields and methods that its objects will have.
Q2 What is an object?
An instance of a class with its own copy of instance fields.
Q3 Difference between class and object?
Class is a definition; object is a concrete runtime instance with state.
Q4 What does new do?
Allocates memory on the heap, runs the constructor, and returns a reference to the new object.
Q5 What is the this keyword?
A reference to the current object; resolves naming conflicts with parameters.

FAQ

FAQ 1 How many objects can a class create?
Unlimited — only memory limits the count.
FAQ 2 Where are objects stored?
On the heap; references live on the stack.
FAQ 3 Can a class have no fields?
Yes — utility classes often have only static methods.
FAQ 4 Can a class have no methods?
Yes — but it would just be a record-like data holder; consider using record.
FAQ 5 Are class names case-sensitive?
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

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Switch Case Constructor OOP Best Practices

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

TIP 01 Use clear, descriptive identifiers when writing code involving Class and Object — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
Class and ObjectClass and Object conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Switch Case — strengthens your understanding of the previous building block.
NEXT Constructor — the natural progression after mastering Class and Object.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore 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.

Continue Learning