LearnContact
Lesson 1775 min read

Classes in Java

Learn how to define classes in Java, create custom data types, declare fields and methods, understand class structure, access modifiers, static members, nested classes, and design reusable program blueprints.

Introduction

In the previous lessons, you learned variables, methods, arrays, and Strings. These features allow you to store data and perform operations, but real applications contain many related values and behaviors that need to be organized together. Java solves this problem using classes.

Simple Class
class Student {

    String name;

    int age;

    void study() {

        System.out.println(
                name + " is studying"
        );

    }

}

A class combines related data and behavior into one reusable structure. Classes are the foundation of Object-Oriented Programming in Java and are used to represent real-world entities, application components, services, utilities, and business concepts.

What You Will Learn
  • What a class is.
  • Why classes are needed.
  • How classes act as blueprints.
  • How to define a class.
  • How to create custom data types.
  • What class members are.
  • How fields work.
  • How methods work inside classes.
  • How Java source files contain classes.
  • How public classes work.
  • The relationship between class names and file names.
  • How default field values work.
  • The difference between fields and local variables.
  • How class reference variables work.
  • How to access class members.
  • How the dot operator works.
  • What null references are.
  • What anonymous objects are.
  • How methods use fields.
  • How methods update class data.
  • How the this keyword works.
  • What variable shadowing is.
  • How access modifiers work.
  • How private members work.
  • How default access works.
  • How protected members work.
  • How public members work.
  • How static members work.
  • How static fields work.
  • How static methods work.
  • The difference between instance and static members.
  • How static blocks work.
  • How instance initialization blocks work.
  • How class initialization order works.
  • How final affects classes, fields, and methods.
  • What nested classes are.
  • How static nested classes work.
  • How inner classes work.
  • What local classes are.
  • What anonymous classes are.
  • How classes are loaded.
  • How classes and references are stored in memory.
  • The difference between stack and heap memory.
  • How multiple classes relate to each other.
  • What association is.
  • What aggregation is.
  • What composition is.
  • How utility classes are designed.
  • How immutable classes are designed.
  • What data classes are.
  • What service classes are.
  • How to design real-world classes.
  • How Single Responsibility improves class design.
  • What high cohesion means.
  • What low coupling means.
  • Common class errors.
  • Best practices for designing classes.

What is a Class?

A class is a user-defined blueprint or template that describes the data and behavior of a particular type of entity.

Basic Class
class Car {

    String brand;

    int speed;

    void drive() {

        System.out.println(
                "Car is driving"
        );

    }

}
Class Concept
CLASS: CAR

┌─────────────────────────────┐
│            DATA             │
│                             │
│  brand                      │
│  speed                      │
│                             │
├─────────────────────────────┤
│          BEHAVIOR           │
│                             │
│  drive()                    │
│                             │
└─────────────────────────────┘
Class Definition
  • A class is a blueprint.
  • A class is a user-defined data type.
  • A class can contain fields.
  • A class can contain methods.
  • A class can contain constructors.
  • A class can contain blocks.
  • A class can contain nested classes.
  • A class groups related data and behavior.

Why Classes are Needed

Organization

Classes group related data and behavior into meaningful units.

Reusability

One class definition can be used to create and manage many similar entities.

Modularity

Large applications can be divided into smaller independent classes.

Data Protection

Classes can control access to internal data using access modifiers.

Real-World Modeling

Classes can represent students, products, accounts, orders, employees, and other concepts.

Maintainability

Well-designed classes make programs easier to understand, test, modify, and extend.

Real-World Analogy

Think of a class as the architectural blueprint of a house. The blueprint defines what every house of that design should contain, but the blueprint itself is not the actual house.

Blueprint Analogy
HOUSE BLUEPRINT

┌──────────────────────────┐
│ Rooms                    │
│ Doors                    │
│ Windows                  │
│ Kitchen                  │
│ Bathrooms                │
└──────────────────────────┘

          │
          │ USED TO BUILD
          ▼

┌────────────┐
│  HOUSE 1   │
└────────────┘

┌────────────┐
│  HOUSE 2   │
└────────────┘

┌────────────┐
│  HOUSE 3   │
└────────────┘


CLASS

Defines structure and behavior


OBJECTS

Actual entities created
from the class

Class as a Blueprint

Student Blueprint
class Student {

    String name;

    int age;

    void study() {

        System.out.println(
                "Student is studying"
        );

    }

}
Blueprint Structure
STUDENT CLASS

┌───────────────────────────┐
│          FIELDS           │
│                           │
│  name                     │
│  age                      │
│                           │
├───────────────────────────┤
│          METHODS          │
│                           │
│  study()                  │
│                           │
└───────────────────────────┘

CLASS DEFINES:

WHAT DATA EXISTS

AND

WHAT BEHAVIOR EXISTS

Class Syntax

General Syntax
accessModifier class ClassName {

    // Fields

    // Constructors

    // Methods

    // Blocks

    // Nested Classes

}
Example
public class Employee {

    String name;

    double salary;

    void work() {

        System.out.println(
                "Employee is working"
        );

    }

}
Class Naming Convention
  • Class names normally use PascalCase.
  • Each major word begins with an uppercase letter.
  • Use meaningful nouns for class names.
  • Examples include Student, BankAccount, ProductService, and OrderManager.

Creating Your First Class

Student.java
class Student {

    String name;

    int age;

    void introduce() {

        System.out.println(
                "My name is " + name
        );

        System.out.println(
                "My age is " + age
        );

    }

}

This class defines two fields and one method. The fields represent student data, while the method represents student behavior.

Class Members

Class Members
CLASS MEMBERS

├── Fields
│
├── Methods
│
├── Constructors
│
├── Initialization Blocks
│
└── Nested Types

Members are declarations that belong to a class. The most common members for beginners are fields and methods.

Fields

Fields are variables declared directly inside a class but outside methods, constructors, and blocks. They represent the state or data of the class.

Fields
class Product {

    String name;

    double price;

    int quantity;

}
Product State
PRODUCT DATA

name       ─────► Product Name

price      ─────► Product Price

quantity   ─────► Available Quantity

Methods

Methods define actions or behavior associated with a class.

Methods
class Calculator {

    void showMessage() {

        System.out.println(
                "Calculator Ready"
        );

    }

    int add(
        int first,
        int second
    ) {

        return first + second;

    }

}

Class Structure

Complete Structure
public class Employee {

    // Static Field

    static String company =
            "PrograMinds";


    // Instance Fields

    String name;

    double salary;


    // Static Block

    static {

        System.out.println(
                "Class Initialized"
        );

    }


    // Instance Block

    {

        System.out.println(
                "Instance Initialization"
        );

    }


    // Constructor

    Employee() {

        System.out.println(
                "Constructor Called"
        );

    }


    // Instance Method

    void work() {

        System.out.println(
                name + " is working"
        );

    }


    // Static Method

    static void showCompany() {

        System.out.println(company);

    }


    // Nested Class

    static class Department {

    }

}

Multiple Classes in One File

Main.java
class Student {

}

class Teacher {

}

public class Main {

    public static void main(
        String[] args
    ) {

        System.out.println(
                "Program Started"
        );

    }

}

A Java source file can contain multiple classes, but only one top-level public class is normally allowed in a single source file.

Public Classes

Public Class
public class Student {

}
Public Class Rule
  • A source file can contain at most one public top-level class.
  • The source file name must match the public class name.
  • Java class names are case-sensitive.

Class and File Names

Correct Naming
FILE

Student.java


PUBLIC CLASS

public class Student {

}


CORRECT

Student.java
        │
        └────► Student
Incorrect Naming
FILE

student.java


PUBLIC CLASS

public class Student {

}


INCORRECT

File name does not exactly match
the public class name

Creating Custom Data Types

A class creates a new reference type. After defining a class, the class name can be used as a data type.

Custom Type
class Student {

    String name;

    int age;

}


public class Main {

    public static void main(
        String[] args
    ) {

        Student student;

    }

}
Type Comparison
BUILT-IN TYPES

int number;

double price;

String name;


CUSTOM TYPE

Student student;

Employee employee;

Product product;

Default Field Values

Instance and static fields automatically receive default values when no explicit value is assigned.

Default Values
TYPE              DEFAULT VALUE

byte              0

short             0

int               0

long              0L

float             0.0f

double            0.0

char              '\u0000'

boolean           false

Reference Type    null
Default Fields
class Student {

    String name;

    int age;

    boolean active;

}
Local Variables are Different
  • Fields receive default values.
  • Local variables do not receive automatic default values.
  • Local variables must be initialized before use.

Local Variables vs Instance Variables

Variable Locations
class Student {

    String name;

    void showAge() {

        int age = 25;

        System.out.println(age);

    }

}
Comparison
INSTANCE VARIABLE

String name;

Declared inside class
but outside methods

Belongs to an object

Receives default value


LOCAL VARIABLE

int age = 25;

Declared inside method or block

Exists during method execution

Must be initialized before use

Accessing Class Members

Instance members are accessed through a reference that points to an object. Static members are normally accessed through the class name.

Member Access
student.name

student.study()

Student.college

Student.showCollege()

The dot Operator

Dot Operator
reference.member

student.name

student.age

student.study()


ClassName.staticMember

Student.college

Student.showCollege()

The dot operator is used to access members through an object reference or class name.

Class Reference Variables

A variable whose type is a class stores a reference to an object rather than storing the complete object directly.

Reference Variable
Student student =
        new Student();
Reference Concept
STACK                         HEAP

┌──────────────┐             ┌──────────────┐
│   student    │────────────►│ Student      │
│  reference   │             │ Object       │
└──────────────┘             └──────────────┘

null Class References

null Reference
Student student = null;
Meaning
student

   │
   ▼

null

NO OBJECT REFERENCED
NullPointerException
  • A null reference does not point to an object.
  • Accessing an instance field through null causes NullPointerException.
  • Calling an instance method through null causes NullPointerException.
  • Validate uncertain references before using them.

Anonymous Objects

An anonymous object is created without storing its reference in a variable.

Anonymous Object
new Student().study();
Comparison
NAMED REFERENCE

Student student =
        new Student();

student.study();


ANONYMOUS OBJECT

new Student().study();
When Anonymous Objects are Useful
  • The object is needed only once.
  • No later access to the same object is required.
  • The expression remains readable.

Methods Inside Classes

Class Methods
class Student {

    void study() {

        System.out.println(
                "Student is studying"
        );

    }

    void sleep() {

        System.out.println(
                "Student is sleeping"
        );

    }

}

Methods with Parameters

Method Parameters
class Calculator {

    void add(
        int first,
        int second
    ) {

        int result =
                first + second;

        System.out.println(result);

    }

}

Methods with Return Values

Return Value
class Calculator {

    int add(
        int first,
        int second
    ) {

        return first + second;

    }

}

Methods Using Fields

Use Class Fields
class Rectangle {

    double length;

    double width;

    double calculateArea() {

        return length * width;

    }

}

Instance methods can directly access the instance fields of the current object.

Updating Fields

Update Field
class BankAccount {

    double balance;

    void deposit(double amount) {

        balance =
                balance + amount;

    }

    void withdraw(double amount) {

        balance =
                balance - amount;

    }

}

The this Keyword

The this keyword refers to the current object whose instance method or constructor is executing.

Using this
class Student {

    String name;

    void setName(String name) {

        this.name = name;

    }

}
this Meaning
this.name = name;

     │        │
     │        └── METHOD PARAMETER
     │
     └─────────── CURRENT OBJECT FIELD

Variable Shadowing

Variable shadowing occurs when a local variable or parameter has the same name as a field.

Without this
class Student {

    String name;

    void setName(String name) {

        name = name;

    }

}

In this example, both names refer to the parameter, so the field is not updated.

With this
class Student {

    String name;

    void setName(String name) {

        this.name = name;

    }

}

Access Modifiers

Access modifiers control where classes and class members can be accessed.

Access Modifiers
ACCESS MODIFIERS

├── private
│
├── default
│
├── protected
│
└── public

private Members

Private Field
class BankAccount {

    private double balance;

}

A private member can be accessed only inside the class where it is declared.

default Access

Package-Private Field
class Student {

    String name;

}

When no access modifier is written, the member receives package-private access and can be accessed by classes in the same package.

protected Members

Protected Field
class Person {

    protected String name;

}

Protected members are accessible in the same package and also through inheritance rules in subclasses.

public Members

Public Method
class Student {

    public void study() {

        System.out.println(
                "Studying"
        );

    }

}

Public members can be accessed from any class where the containing class itself is accessible.

Access Modifier Comparison

Access Table
MODIFIER     SAME CLASS   SAME PACKAGE   SUBCLASS   EVERYWHERE

private          YES            NO            NO          NO

default          YES            YES           NO*         NO

protected        YES            YES           YES         NO

public           YES            YES           YES         YES


* A subclass in the same package can access
  default members because it is in the same package.

Static Members

A static member belongs to the class itself rather than to an individual object.

Member Ownership
INSTANCE MEMBER

Belongs to each object


STATIC MEMBER

Belongs to the class

Static Fields

Static Field
class Student {

    static String college =
            "PrograMinds Academy";

    String name;

}
Shared Static Field
STUDENT CLASS

college = "PrograMinds Academy"

        ▲
        │
   SHARED BY ALL
        │

┌──────────┐  ┌──────────┐  ┌──────────┐
│ Student1 │  │ Student2 │  │ Student3 │
└──────────┘  └──────────┘  └──────────┘

Static Methods

Static Method
class Calculator {

    static int add(
        int first,
        int second
    ) {

        return first + second;

    }

}
Call Static Method
int result =
        Calculator.add(
            10,
            20
        );

Instance vs Static Members

Comparison
INSTANCE MEMBER

Belongs to object

Each object can have different value

Accessed through object reference

Can directly access instance members

Can directly access static members


STATIC MEMBER

Belongs to class

Shared at class level

Accessed through class name

Cannot directly access instance members

Can directly access static members

Accessing Static Members

Recommended Access
class Student {

    static String college =
            "PrograMinds Academy";

}


public class Main {

    public static void main(
        String[] args
    ) {

        System.out.println(
                Student.college
        );

    }

}
Recommended Style
  • Access static fields through the class name.
  • Access static methods through the class name.
  • This clearly communicates that the member belongs to the class.

Static Restrictions

Invalid Direct Access
class Student {

    String name;

    static void show() {

        // System.out.println(name);

    }

}

A static method does not execute for a specific object, so it cannot directly access an instance field or instance method.

Static Context Rules
  • Static methods can directly access static members.
  • Static methods cannot directly access instance members.
  • The this keyword cannot be used in a static context.
  • An object reference is required to access instance members from static code.

Static Blocks

A static initialization block runs when the class is initialized.

Static Block
class Database {

    static String connection;

    static {

        connection =
                "Database Connected";

        System.out.println(
                connection
        );

    }

}

Instance Initialization Blocks

An instance initialization block runs whenever an object is created, before the constructor body executes.

Instance Block
class Student {

    {

        System.out.println(
                "Instance Block"
        );

    }

    Student() {

        System.out.println(
                "Constructor"
        );

    }

}

Initialization Order

Simplified Order
CLASS INITIALIZATION

1. Static Fields

2. Static Blocks


OBJECT CREATION

1. Instance Fields

2. Instance Initialization Blocks

3. Constructor Body
Important
  • Static initialization occurs when the class is initialized.
  • Instance initialization occurs for each object.
  • Instance blocks execute before the constructor body.
  • Initialization details become more important in inheritance.

Final Classes

Final Class
final class SecurityManager {

}

A final class cannot be extended by another class.

Final Fields

Final Field
class Circle {

    final double PI =
            3.14159;

}

A final field can be assigned only once. Static final fields are commonly used for class constants.

Class Constant
class MathConstants {

    static final double PI =
            3.14159;

}

Final Methods

Final Method
class Parent {

    final void show() {

        System.out.println(
                "Final Method"
        );

    }

}

A final method cannot be overridden by a subclass. Method overriding will be covered in the Polymorphism lesson.

Nested Classes

A class declared inside another class is called a nested class.

Nested Class Types
NESTED CLASSES

├── Static Nested Class
│
└── Inner Class
     │
     ├── Member Inner Class
     │
     ├── Local Class
     │
     └── Anonymous Class

Static Nested Classes

Static Nested Class
class Outer {

    static class Nested {

        void show() {

            System.out.println(
                    "Nested Class"
            );

        }

    }

}
Create Nested Object
Outer.Nested nested =
        new Outer.Nested();

nested.show();

Inner Classes

Member Inner Class
class Outer {

    private String message =
            "Hello";

    class Inner {

        void show() {

            System.out.println(
                    message
            );

        }

    }

}

A non-static nested class is called an inner class. An inner class is associated with an instance of the outer class.

Local Classes

Local Class
class Outer {

    void process() {

        class LocalHelper {

            void help() {

                System.out.println(
                        "Helping"
                );

            }

        }

        LocalHelper helper =
                new LocalHelper();

        helper.help();

    }

}

A local class is declared inside a method, constructor, or block and is available only within that scope.

Anonymous Classes

An anonymous class is a class without an explicit name. It is declared and instantiated in one expression.

Anonymous Class Concept
Runnable task =
        new Runnable() {

            @Override
            public void run() {

                System.out.println(
                        "Task Running"
                );

            }

        };

task.run();
Later Topics
  • Anonymous classes are often used with interfaces and abstract classes.
  • Interfaces are covered in a later lesson.
  • Modern Java often replaces simple anonymous functional implementations with lambda expressions.

Class Loading

Before Java can use a class, the JVM must make its class definition available at runtime. This process involves class loading and initialization.

Simplified Process
SOURCE CODE

Student.java

      │
      ▼

COMPILATION

Student.class

      │
      ▼

CLASS LOADER

Loads class definition

      │
      ▼

JVM

Uses class at runtime

Classes in Memory

At runtime, class metadata, static members, objects, references, and method execution data are managed in different JVM runtime memory areas.

Simplified Memory View
JVM MEMORY

┌───────────────────────────────┐
│ CLASS METADATA                │
│                               │
│ Class structure               │
│ Method information            │
│ Runtime type information      │
└───────────────────────────────┘

┌───────────────────────────────┐
│ HEAP                          │
│                               │
│ Objects                       │
│ Instance data                 │
└───────────────────────────────┘

┌───────────────────────────────┐
│ STACK                         │
│                               │
│ Method frames                 │
│ Local variables               │
│ References                    │
└───────────────────────────────┘
Simplified Model
  • This is a conceptual beginner-friendly model.
  • Actual JVM memory management contains additional technical details.
  • The important idea is that class definitions, objects, and local execution data serve different purposes.

Stack and Heap

Reference and Object
Student student =
        new Student();
Simplified Memory
STACK                         HEAP

┌──────────────┐             ┌────────────────┐
│ student      │────────────►│ Student Object │
│ reference    │             │                │
└──────────────┘             │ name           │
                             │ age            │
                             └────────────────┘

Class Objects

Every loaded Java type can be represented at runtime by an object of the Class class. This allows Java programs to inspect type information.

Class Object
Class<Student> type =
        Student.class;

System.out.println(
        type.getName()
);
Reflection Foundation
  • Class objects represent runtime type information.
  • They are used by Java reflection.
  • Frameworks frequently inspect classes at runtime.
  • Reflection is an advanced topic.

Class Relationships

Real applications contain multiple classes that work together. Common relationships include association, aggregation, composition, and inheritance.

Relationships
CLASS RELATIONSHIPS

├── Association
│
├── Aggregation
│
├── Composition
│
└── Inheritance

Association

Association is a general relationship where one class uses or interacts with another class.

Association
class Teacher {

    void teach(Student student) {

        System.out.println(
                "Teaching student"
        );

    }

}
Relationship
TEACHER

   │
   │ INTERACTS WITH
   ▼

STUDENT

Aggregation

Aggregation represents a has-a relationship where the contained object can exist independently of the container.

Aggregation
class Department {

    Employee employee;

}
Aggregation Concept
DEPARTMENT

HAS AN

EMPLOYEE


EMPLOYEE CAN EXIST

WITHOUT THE DEPARTMENT

Composition

Composition is a stronger has-a relationship where the contained part is strongly owned by the containing object.

Composition
class House {

    private Room room =
            new Room();

}


class Room {

}
Composition Concept
HOUSE

STRONGLY OWNS

ROOM


LIFECYCLE IS TIGHTLY CONNECTED

Utility Classes

A utility class groups related helper methods that do not require object-specific state.

Utility Class
final class MathUtility {

    private MathUtility() {

    }

    static int square(int number) {

        return number * number;

    }

    static int cube(int number) {

        return number
                * number
                * number;

    }

}
Use Utility Class
int result =
        MathUtility.square(5);

Immutable Class Basics

An immutable class is designed so that its object state cannot change after creation.

Simple Immutable Class
final class User {

    private final String name;

    User(String name) {

        this.name = name;

    }

    String getName() {

        return name;

    }

}
Basic Immutable Design
  • Prevent unwanted extension when appropriate.
  • Make state fields private.
  • Use final fields when values should be assigned once.
  • Initialize state during construction.
  • Do not provide methods that modify state.
  • Handle mutable referenced objects carefully.

Data Classes

A data-oriented class primarily represents information used by the application.

Product Data Class
class Product {

    String name;

    double price;

    int quantity;

}

In professional applications, data classes usually apply stronger encapsulation and may use constructors, getters, records, validation, or mapping frameworks.

Service Classes

A service class focuses on application operations or business behavior.

Service Class
class PaymentService {

    void processPayment(
        double amount
    ) {

        System.out.println(
                "Processing payment: "
                + amount
        );

    }

}

Real-World Student Class

Student.java
class Student {

    String name;

    int age;

    double marks;


    void study() {

        System.out.println(
                name + " is studying"
        );

    }


    boolean hasPassed() {

        return marks >= 40;

    }


    void showDetails() {

        System.out.println(
                "Name: " + name
        );

        System.out.println(
                "Age: " + age
        );

        System.out.println(
                "Marks: " + marks
        );

    }

}

Bank Account Class

BankAccount.java
class BankAccount {

    private String accountNumber;

    private double balance;


    void deposit(double amount) {

        if (amount > 0) {

            balance += amount;

        }

    }


    void withdraw(double amount) {

        if (
            amount > 0
            && amount <= balance
        ) {

            balance -= amount;

        }

    }


    double getBalance() {

        return balance;

    }

}

Product Class

Product.java
class Product {

    String name;

    double price;

    int quantity;


    double calculateTotal() {

        return price * quantity;

    }


    boolean isAvailable() {

        return quantity > 0;

    }


    void showDetails() {

        System.out.println(
                "Product: " + name
        );

        System.out.println(
                "Price: " + price
        );

        System.out.println(
                "Quantity: " + quantity
        );

        System.out.println(
                "Total: "
                + calculateTotal()
        );

    }

}

Employee Class

Employee.java
class Employee {

    static String company =
            "PrograMinds";

    String name;

    double salary;


    void work() {

        System.out.println(
                name + " is working"
        );

    }


    double calculateAnnualSalary() {

        return salary * 12;

    }


    static void showCompany() {

        System.out.println(
                "Company: " + company
        );

    }

}

Class Design Process

Design Process
STEP 1

IDENTIFY THE CONCEPT

Example:
Bank Account


STEP 2

IDENTIFY DATA

accountNumber
balance
ownerName


STEP 3

IDENTIFY BEHAVIOR

deposit()
withdraw()
showBalance()


STEP 4

CONTROL ACCESS

private fields
public operations


STEP 5

VALIDATE RULES

amount > 0
amount <= balance


STEP 6

KEEP RESPONSIBILITY FOCUSED

BankAccount manages
bank account behavior

Single Responsibility

A well-designed class should have one clear primary responsibility and one main reason to change.

Poor Design
USER CLASS

├── Stores User Data
├── Sends Emails
├── Generates PDF Reports
├── Connects to Database
├── Processes Payments
└── Creates Backups


TOO MANY RESPONSIBILITIES
Better Design
User

Stores user information


EmailService

Sends emails


ReportService

Generates reports


UserRepository

Handles persistence


PaymentService

Processes payments

High Cohesion

High cohesion means that the data and behavior inside a class are closely related to one focused purpose.

High Cohesion
BANK ACCOUNT CLASS

balance

deposit()

withdraw()

getBalance()


ALL MEMBERS RELATE TO

BANK ACCOUNT MANAGEMENT

Low Coupling

Low coupling means classes depend on each other as little as reasonably possible.

Coupling Concept
HIGH COUPLING

Class A
depends heavily on
Class B internals

Small changes spread widely


LOW COUPLING

Class A
uses a clear interface
to work with Class B

Internal changes have
less impact

Common Class Errors

Common Errors
CLASS ERRORS

├── Using Incorrect Class Naming
├── File Name Not Matching Public Class
├── Declaring Multiple Public Top-Level Classes
├── Forgetting class Keyword
├── Missing Class Braces
├── Declaring Methods Outside Class
├── Declaring Fields Inside Wrong Scope
├── Confusing Fields and Local Variables
├── Expecting Local Variables to Have Default Values
├── Forgetting Fields Receive Default Values
├── Using an Uninitialized Local Variable
├── Accessing Instance Members Without an Object
├── Accessing Instance Members Through null
├── Causing NullPointerException
├── Confusing Reference and Object
├── Assuming Assignment Copies an Object
├── Incorrect Use of Dot Operator
├── Incorrect Use of this
├── Using this in Static Context
├── Variable Shadowing
├── Writing name = name Instead of this.name = name
├── Exposing Sensitive Fields Publicly
├── Choosing Wrong Access Modifier
├── Accessing private Members Outside Class
├── Confusing default Access with public
├── Misunderstanding protected Access
├── Accessing Static Members Through Objects
├── Treating Static Fields as Per-Object Data
├── Accessing Instance Fields Directly from Static Methods
├── Calling Instance Methods Directly from Static Context
├── Forgetting Static Members are Shared
├── Incorrect Static Initialization
├── Misunderstanding Initialization Order
├── Reassigning Final Fields
├── Trying to Extend a Final Class
├── Trying to Override a Final Method
├── Creating Unnecessary Nested Classes
├── Confusing Static Nested and Inner Classes
├── Creating God Classes
├── Giving One Class Too Many Responsibilities
├── Mixing Data Access and Business Logic Carelessly
├── High Coupling Between Classes
├── Low Cohesion
├── Poor Class Names
├── Poor Field Names
├── Poor Method Names
├── Creating Classes Without Clear Purpose
├── Using Static for Everything
├── Using Objects for Everything
├── Ignoring Validation
├── Duplicating Logic Across Classes
├── Exposing Internal Implementation Details
├── Creating Circular Dependencies
├── Mixing Utility Methods with Instance State
└── Designing Before Understanding the Problem

Best Practices

  • Use PascalCase for class names.
  • Use meaningful noun-based class names.
  • Keep one major public class per source file.
  • Match the public class name with the source file name.
  • Give each class a clear purpose.
  • Keep related data and behavior together.
  • Prefer small focused classes over very large classes.
  • Use fields to represent persistent object state.
  • Use local variables for temporary method data.
  • Remember that fields receive default values.
  • Initialize local variables before use.
  • Use meaningful field names.
  • Use meaningful method names.
  • Use private fields for internal state when appropriate.
  • Expose behavior instead of unnecessary internal data.
  • Choose the narrowest suitable access modifier.
  • Avoid making every member public.
  • Use this when field and parameter names are the same.
  • Avoid confusing variable shadowing.
  • Use static only for class-level state or behavior.
  • Access static members through the class name.
  • Do not store object-specific data in static fields.
  • Remember that static methods do not have a current object.
  • Do not use this in static contexts.
  • Use static final for shared constants.
  • Use uppercase names for constants.
  • Use final classes when inheritance should be prevented.
  • Use final fields when values should be assigned once.
  • Use nested classes only when the relationship is strong and clear.
  • Use static nested classes when an outer object is not required.
  • Use inner classes when behavior logically depends on an outer instance.
  • Avoid unnecessary anonymous classes.
  • Use utility classes for stateless related helper operations.
  • Prevent utility class instantiation when appropriate.
  • Design immutable classes carefully.
  • Use composition for strong ownership relationships.
  • Use aggregation when related objects can exist independently.
  • Keep class dependencies limited.
  • Aim for high cohesion.
  • Aim for low coupling.
  • Follow the Single Responsibility Principle.
  • Avoid God classes.
  • Move unrelated behavior into separate classes.
  • Validate data before changing object state.
  • Keep business rules close to the relevant domain class or service.
  • Avoid exposing mutable internal data unnecessarily.
  • Do not duplicate the same logic across multiple classes.
  • Create helper methods for repeated internal behavior.
  • Keep methods focused.
  • Document unusual class responsibilities.
  • Use packages to organize related classes.
  • Test classes independently.
  • Test null handling where references may be absent.
  • Test default field states.
  • Test valid state changes.
  • Test invalid state changes.
  • Test static shared behavior.
  • Test class relationships.
  • Refactor classes that become too large.
  • Prefer clarity over clever class structures.
  • Design classes around real responsibilities rather than arbitrary grouping.

Class Selection Guide

Class Design Guide
NEED TO REPRESENT A CONCEPT?

        │
        ├── NO ──────► MAY NOT NEED A CLASS
        │
        └── YES
              │
              ▼

DOES IT HAVE DATA AND BEHAVIOR?

        │
        ├── YES ─────► DOMAIN CLASS
        │
        └── NO
              │
              ▼

ONLY RELATED HELPER OPERATIONS?

        │
        ├── YES ─────► UTILITY CLASS
        │
        └── NO
              │
              ▼

MAINLY APPLICATION OPERATIONS?

        │
        ├── YES ─────► SERVICE CLASS
        │
        └── NO
              │
              ▼

MAINLY REPRESENTS DATA?

        │
        ├── YES ─────► DATA CLASS
        │
        └── NO ──────► RECHECK RESPONSIBILITY


DOES DATA BELONG TO EACH OBJECT?

        │
        ├── YES ─────► INSTANCE FIELD
        │
        └── NO
              │
              ▼

SHARED BY ENTIRE CLASS?

        │
        ├── YES ─────► STATIC FIELD
        │
        └── NO ──────► RECHECK DESIGN


DOES METHOD NEED OBJECT STATE?

        │
        ├── YES ─────► INSTANCE METHOD
        │
        └── NO
              │
              ▼

LOGIC BELONGS TO CLASS?

        │
        ├── YES ─────► STATIC METHOD
        │
        └── NO ──────► CONSIDER ANOTHER CLASS

Class Checklist

Checklist
CLASS CHECKLIST

[ ] Class has a clear responsibility

[ ] Class name uses PascalCase

[ ] Class name is meaningful

[ ] Public class matches file name

[ ] Only one public top-level class exists per file

[ ] Fields represent meaningful state

[ ] Field names are clear

[ ] Methods represent meaningful behavior

[ ] Method names are clear

[ ] Fields and local variables are distinguished

[ ] Local variables are initialized before use

[ ] Default field values are understood

[ ] Instance members belong to objects

[ ] Static members belong to the class

[ ] Static is not used unnecessarily

[ ] Static members are accessed through class name

[ ] Object-specific data is not static

[ ] null references are handled

[ ] Instance members are not accessed through null

[ ] Reference assignment behavior is understood

[ ] this is used correctly

[ ] Variable shadowing is handled

[ ] Access modifiers are intentional

[ ] Sensitive state is not unnecessarily public

[ ] private is used for internal implementation

[ ] package access is intentional

[ ] protected access is intentional

[ ] public API is intentionally exposed

[ ] Final fields are assigned correctly

[ ] Constants use static final when appropriate

[ ] Nested classes have a clear reason

[ ] Static nested class does not need outer instance

[ ] Inner class genuinely depends on outer instance

[ ] Utility class contains stateless helper behavior

[ ] Utility class instantiation is prevented when appropriate

[ ] Class relationships are clear

[ ] Association is used intentionally

[ ] Aggregation is used intentionally

[ ] Composition is used intentionally

[ ] Class has high cohesion

[ ] Class has low coupling

[ ] Single Responsibility is followed

[ ] God class is avoided

[ ] Validation protects object state

[ ] Repeated logic is not duplicated

[ ] Internal details are not unnecessarily exposed

[ ] Circular dependencies are avoided

[ ] Class can be tested independently

[ ] Default state is tested

[ ] Valid behavior is tested

[ ] Invalid behavior is tested

[ ] null scenarios are tested

[ ] Static shared behavior is tested

[ ] Class is refactored when responsibility grows too large

Common Misconceptions

Avoid These Misconceptions
  • A class is not the same as an object.
  • A class defines a type.
  • An object is an instance created from a class.
  • A class can exist without creating objects.
  • A class can contain both data and behavior.
  • Fields are not the same as local variables.
  • Fields receive default values.
  • Local variables do not automatically receive usable default values.
  • A class variable can store an object reference.
  • The reference is not the object itself.
  • Assigning one reference to another does not normally copy the object.
  • A null reference does not point to an object.
  • Calling an instance method through null causes NullPointerException.
  • The dot operator accesses members.
  • The this keyword refers to the current object.
  • The this keyword cannot be used in a static context.
  • Static members belong to the class.
  • Instance members belong to objects.
  • Static fields are shared.
  • Each object does not receive a separate static field.
  • Static methods cannot directly access instance members.
  • Public does not mean every field should be public.
  • Private members are accessible inside their own class.
  • Default access means package-private access.
  • Protected is not simply public for subclasses.
  • A final class cannot be extended.
  • A final field can be assigned only once.
  • A final method cannot be overridden.
  • A static nested class does not require an outer class instance.
  • An inner class is associated with an outer object.
  • A source file can contain multiple non-public classes.
  • Only one top-level public class is normally allowed per source file.
  • The public class name must match the source file name.
  • Not every method should be static.
  • Not every piece of data should become a class.
  • A large class is not automatically a better class.
  • More classes do not automatically mean better design.
  • Good classes have clear responsibilities.
  • High cohesion is desirable.
  • Low coupling is desirable.
  • Composition and aggregation are not identical.
  • Utility classes should not contain unrelated methods.
  • Immutable classes require more than simply using final on the class.
  • Good class design depends on understanding the problem domain.

Practice Exercises

Exercise 1: Student Class
  • Create a Student class.
  • Add name, age, and marks fields.
  • Create a study method.
  • Create a showDetails method.
  • Create a method that returns whether the student passed.
Exercise 2: Rectangle Class
  • Create length and width fields.
  • Create calculateArea.
  • Create calculatePerimeter.
  • Create showDetails.
  • Test different field values.
Exercise 3: Bank Account
  • Create a private balance field.
  • Create deposit behavior.
  • Create withdraw behavior.
  • Reject invalid amounts.
  • Create a method to view the balance.
Exercise 4: Product Class
  • Create name, price, and quantity fields.
  • Calculate total inventory value.
  • Check whether the product is available.
  • Reduce quantity after a sale.
  • Reject invalid sale quantities.
Exercise 5: Static Members
  • Create a Student class.
  • Add an instance name field.
  • Add a static college field.
  • Create multiple student objects.
  • Verify that the college value is shared.
Exercise 6: Utility Class
  • Create a NumberUtility class.
  • Prevent object creation.
  • Create a static square method.
  • Create a static cube method.
  • Create a static isEven method.
Exercise 7: Composition
  • Create an Engine class.
  • Create a Car class.
  • Make Car strongly own an Engine.
  • Create start behavior.
  • Display how the two classes work together.
Exercise 8: Immutable Class
  • Create a final User class.
  • Add private final fields.
  • Initialize values during construction.
  • Provide methods to read values.
  • Do not provide modification methods.
Exercise 9: Class Refactoring
  • Create one class that stores users, sends emails, and generates reports.
  • Identify the design problem.
  • Split responsibilities into focused classes.
  • Explain why the new design has higher cohesion.
  • Explain why the new design is easier to maintain.
Exercise 10: Mini Library Model
  • Create Book, Member, and Library classes.
  • Decide which data belongs to each class.
  • Decide which methods belong to each class.
  • Define relationships between the classes.
  • Keep each class focused on one main responsibility.

Common Interview Questions

What is a class in Java?

A class is a user-defined blueprint or reference type that defines data and behavior.

What can a class contain?

A class can contain fields, methods, constructors, initialization blocks, and nested types.

What is the difference between a class and an object?

A class defines the blueprint or type, while an object is an actual instance created from that class.

What is a field?

A field is a variable declared directly inside a class and outside methods, constructors, and blocks.

Do fields receive default values?

Yes. Instance and static fields receive default values when no explicit value is assigned.

Do local variables receive default values?

Local variables must be definitely assigned before they are read.

What is the this keyword?

The this keyword refers to the current object.

What is variable shadowing?

Variable shadowing occurs when a local variable or parameter has the same name as a field.

What is a static member?

A static member belongs to the class rather than to an individual object.

Can a static method directly access instance fields?

No. It requires an object reference because instance fields belong to objects.

Can this be used in a static method?

No. A static method does not execute for a specific current object.

What is the difference between private and public?

Private members are accessible only inside their declaring class, while public members can be accessed wherever the containing class is accessible.

What is default access?

When no access modifier is specified, the member or top-level class receives package-private access.

What is a final class?

A final class cannot be extended.

What is a nested class?

A nested class is a class declared inside another class.

What is the difference between a static nested class and an inner class?

A static nested class does not require an outer instance, while an inner class is associated with an outer object.

What is association?

Association is a general relationship where one class interacts with another.

What is aggregation?

Aggregation is a has-a relationship where the contained object can exist independently.

What is composition?

Composition is a strong ownership relationship where the contained part has a closely connected lifecycle.

What is high cohesion?

High cohesion means the members of a class are closely related to one focused responsibility.

What is low coupling?

Low coupling means classes have limited dependencies on each other.

Frequently Asked Questions

Can a Java file contain multiple classes?

Yes. A source file can contain multiple classes, but only one top-level public class is normally allowed.

Must every class be public?

No. A top-level class can also use package-private access.

Can a class exist without objects?

Yes. A class definition can exist without any object being created.

Can a class contain only methods?

Yes. Utility classes often contain only static methods and constants.

Can a class contain only fields?

Yes, although professional designs often add controlled behavior or use specialized data structures such as records.

Should every field be private?

Private fields are a strong default for internal state, but the correct access level depends on the design.

Should every method be static?

No. Use static only when behavior belongs to the class and does not require object-specific state.

Can a class be final?

Yes. A final class cannot be extended.

Can one class contain another class?

Yes. Java supports nested and inner classes.

What should I learn after Classes?

The next lesson covers Objects in Java.

Key Takeaways

  • A class is a blueprint.
  • A class is a user-defined reference type.
  • Classes group related data and behavior.
  • Classes are fundamental to Object-Oriented Programming.
  • Fields represent class or object state.
  • Methods represent behavior.
  • Constructors initialize objects.
  • Classes can contain initialization blocks.
  • Classes can contain nested types.
  • Class names normally use PascalCase.
  • A public class name must match its source file name.
  • A source file can contain multiple classes.
  • Only one top-level public class is normally allowed per source file.
  • A class name can be used as a data type.
  • Class variables store object references.
  • Fields receive default values.
  • Local variables must be initialized before use.
  • Instance fields belong to objects.
  • Static fields belong to the class.
  • Instance methods operate on object-specific state.
  • Static methods belong to the class.
  • The dot operator accesses members.
  • A null reference does not point to an object.
  • Accessing instance members through null causes NullPointerException.
  • Anonymous objects are created without storing a reference.
  • Methods can access fields.
  • Methods can update object state.
  • The this keyword refers to the current object.
  • The this keyword resolves field and parameter name conflicts.
  • Variable shadowing occurs when names overlap across scopes.
  • Access modifiers control visibility.
  • Private members are accessible only inside their class.
  • Default access is package-private.
  • Protected members support package and inheritance access.
  • Public members are widely accessible.
  • Static members are shared at class level.
  • Static methods cannot directly access instance members.
  • The this keyword cannot be used in static context.
  • Static blocks run during class initialization.
  • Instance blocks run during object initialization.
  • Instance blocks execute before the constructor body.
  • Final classes cannot be extended.
  • Final fields can be assigned only once.
  • Final methods cannot be overridden.
  • Nested classes are declared inside other classes.
  • Static nested classes do not require an outer object.
  • Inner classes are associated with outer objects.
  • Local classes are declared inside methods or blocks.
  • Anonymous classes have no explicit class name.
  • Classes are loaded before runtime use.
  • Objects are generally allocated on the heap.
  • Local references are commonly associated with method stack frames.
  • Runtime type information is represented through Class objects.
  • Classes can have relationships.
  • Association represents interaction.
  • Aggregation represents independent has-a relationships.
  • Composition represents strong ownership.
  • Utility classes group stateless helper behavior.
  • Immutable classes prevent state changes after creation.
  • Data classes represent application information.
  • Service classes perform application operations.
  • Good class design starts by identifying responsibilities.
  • Single Responsibility keeps classes focused.
  • High cohesion keeps related members together.
  • Low coupling reduces unnecessary dependencies.
  • Large God classes should be avoided.
  • Classes should expose clear behavior.
  • Internal implementation should be protected.
  • Validation should protect valid object state.
  • Good classes are easier to test.
  • Good classes are easier to maintain.
  • Good classes are easier to extend.
  • Classes prepare you for understanding objects, constructors, encapsulation, inheritance, and polymorphism.

Summary

Classes are one of the most important concepts in Java. A class defines a custom type that combines related data and behavior into a reusable structure.

Fields represent state, while methods represent behavior. A class can also contain constructors, initialization blocks, static members, final members, and nested classes.

Instance members belong to individual objects, while static members belong to the class. Understanding this difference is essential for designing correct Java programs.

Access modifiers control visibility and help protect internal implementation details. The this keyword refers to the current object and is commonly used to distinguish fields from parameters.

Classes can interact through relationships such as association, aggregation, and composition. Well-designed classes should have focused responsibilities, high cohesion, and low coupling.

Mastering classes is essential because almost every major Java concept builds on them, including objects, constructors, encapsulation, inheritance, polymorphism, abstraction, interfaces, exceptions, collections, Spring, and enterprise application development.

Lesson 17 Completed
  • You understand what a class is.
  • You understand why classes are needed.
  • You understand the blueprint analogy.
  • You can define a class.
  • You understand class syntax.
  • You can create custom data types.
  • You understand class members.
  • You understand fields.
  • You understand methods.
  • You understand class structure.
  • You know how multiple classes can exist in one file.
  • You understand public classes.
  • You understand class and file naming rules.
  • You understand default field values.
  • You can distinguish fields from local variables.
  • You understand class reference variables.
  • You can access class members.
  • You understand the dot operator.
  • You understand null references.
  • You understand anonymous objects.
  • You can create methods inside classes.
  • You can create methods with parameters.
  • You can create methods with return values.
  • You can use fields inside methods.
  • You can update fields.
  • You understand the this keyword.
  • You understand variable shadowing.
  • You understand access modifiers.
  • You understand private members.
  • You understand default access.
  • You understand protected members.
  • You understand public members.
  • You can compare access modifiers.
  • You understand static members.
  • You understand static fields.
  • You understand static methods.
  • You can distinguish instance and static members.
  • You can access static members correctly.
  • You understand static restrictions.
  • You understand static blocks.
  • You understand instance initialization blocks.
  • You understand initialization order.
  • You understand final classes.
  • You understand final fields.
  • You understand final methods.
  • You understand nested classes.
  • You understand static nested classes.
  • You understand inner classes.
  • You understand local classes.
  • You understand anonymous classes.
  • You understand basic class loading.
  • You understand classes in memory.
  • You understand the basic stack and heap model.
  • You understand Class objects.
  • You understand class relationships.
  • You understand association.
  • You understand aggregation.
  • You understand composition.
  • You understand utility classes.
  • You understand immutable class basics.
  • You understand data classes.
  • You understand service classes.
  • You can design a Student class.
  • You can design a BankAccount class.
  • You can design a Product class.
  • You can design an Employee class.
  • You understand the class design process.
  • You understand Single Responsibility.
  • You understand high cohesion.
  • You understand low coupling.
  • You can identify common class errors.
  • You know class design best practices.
  • You are ready to learn Objects.
Next Lesson →

Objects in Java