Skip to content
Shehara Heshan edited this page Jul 20, 2026 · 3 revisions

# Introduction

  • Java is an object-oriented programming (OOP) language, and at the heart of object-oriented programming are classes. A class is one of the most fundamental concepts in Java because it provides the blueprint for creating objects that represent real-world entities.

  • Every Java application is built using classes. Whether you're creating a simple calculator, a banking system, a game, or a large enterprise application, classes are used to organize code, define data, and implement behavior. They help developers write code that is modular, reusable, maintainable, and easier to understand.

  • A class groups together data (fields) and behavior (methods) into a single unit. Instead of scattering related variables and functions throughout a program, Java encourages developers to encapsulate them within classes. This approach improves code organization, reduces duplication, and makes software easier to extend and maintain.

  • For example, consider a Car. A car has characteristics such as its brand, model, color, and speed, and it can perform actions like starting, stopping, accelerating, and braking. In Java, these characteristics become fields, while the actions become methods inside a Car class.

`public class Car {

// Fields (State)
String brand;
String model;
int year;

// Method (Behavior)
public void start() {
    System.out.println("The car has started.");
}

}`

In this example:

  • **Car **is the class name.
  • brand, model, and **year **are fields that store information about a car.
  • start() is a method that defines an action the car can perform.

A Class Is More Than a Blueprint

A class is often described as a blueprint for creating objects, but this definition only scratches the surface.

A Java class also serves as:

  • A custom data type that defines the structure of related data.
  • A namespace for organizing fields, methods, constructors, nested classes, and constants.
  • A unit of compilation, where each top-level class is compiled into its own .class file.
  • A runtime entity that the JVM loads, verifies, links, and initializes before it can be used.
  • A container for metadata, including annotations, generic information, modifiers, and runtime attributes.
  • The foundation for implementing object-oriented principles such as encapsulation, inheritance, abstraction, and polymorphism.

In other words, a class defines both what something is and what it can do, while also providing the JVM with the information needed to execute that code efficiently.

Internal Representation of a Java Class

flowchart TD
    A["Java Source Code (.java)"] --> B["Java Compiler (javac)"]
    B --> C["Java Bytecode (.class)"]
    C --> D["Class Loader"]
    D --> E["Bytecode Verification"]
    E --> F["Linking"]

    F --> F1["Verification"]
    F1 --> F2["Preparation"]
    F2 --> F3["Resolution"]

    F3 --> G["Class Initialization"]
    G --> H["JVM Runtime"]
    H --> I["Method Execution"]
Loading

During compilation, the Java compiler (javac) translates the source code into platform-independent bytecode. This bytecode is stored in a .class file, which contains:

  • Class name
  • Package information
  • Superclass
  • Implemented interfaces
  • Fields
  • Methods
  • Constructors
  • Constant Pool
  • Access flags
  • Generic signatures
  • Annotations
  • Debug information
  • Attributes

Unlike source code, the JVM never executes .java files directly. It executes the compiled bytecode contained in .class files.

How the JVM Uses Classes

Before any code inside a class can execute, the JVM performs several steps:

  • Loading – The class loader locates and loads the .class file.
  • Verification – Bytecode is validated for correctness and security.
  • Linking – Symbolic references are resolved, and memory is prepared for static fields.
  • Initialization – Static variables and static initialization blocks execute.
  • Execution – Methods can now be invoked.

This process ensures that every class is properly prepared before it participates in program execution.

What Can a Java Class Contain?

  • Fields (instance variables)
  • Static variables
  • Methods
  • Constructors
  • Static initialization blocks
  • Instance initialization blocks
  • Nested classes
  • Inner classes
  • Interfaces
  • Enumerations
  • Record declarations
  • Generic type parameters
  • Constants
  • Annotations

Example

The following example demonstrates several common components that can be defined within a Java class.

public class Employee {

    // Constant
    public static final String COMPANY = "OpenAI";

    // Instance field
    private String name;

    // Static field
    private static int employeeCount;

    // Static initialization block
    static {
        employeeCount = 0;
    }

    // Instance initialization block
    {
        System.out.println("A new Employee object is being created.");
    }

    // Constructor
    public Employee(String name) {
        this.name = name;
        employeeCount++;
    }

    // Instance method
    public void displayInfo() {
        System.out.println("Employee: " + name);
    }

    // Static method
    public static int getEmployeeCount() {
        return employeeCount;
    }

    // Static nested class
    static class Department {

        private String departmentName;

        public Department(String departmentName) {
            this.departmentName = departmentName;
        }

        public void displayDepartment() {
            System.out.println("Department: " + departmentName);
        }
    }

    // Enum
    enum Status {
        ACTIVE,
        INACTIVE
    }

}

Characteristics of Java Classes

Java classes have several important characteristics:

  • They are reference types.
  • They can define both state and behavior.
  • They support encapsulation through access modifiers.
  • They can inherit from one superclass.
  • They can implement multiple interfaces.
  • They participate in polymorphism through method overriding.
  • They are compiled independently into bytecode.
  • They are loaded dynamically by the JVM.
  • They support reflection at runtime.
  • They are managed by the JVM throughout their lifecycle.

Types of Java Classes

Class Type Description Can Be Instantiated? Common Use Case
Concrete Class A fully implemented class that provides complete implementations for all its methods. ✅ Yes General-purpose classes used to create objects.
Abstract Class A class declared with the abstract keyword that cannot be instantiated and may contain both abstract and concrete methods. ❌ No Providing a common base for related subclasses.
Final Class A class declared with the final keyword that cannot be extended by other classes. ✅ Yes Creating immutable or secure classes that should not be inherited.
Static Nested Class A class declared with the static keyword inside another class. It does not require an instance of the enclosing class. ✅ Yes Grouping helper classes that logically belong to an outer class.
Inner Class A non-static nested class that has access to all members of its enclosing class, including private members. ✅ Yes (requires an outer class instance) Modeling components that are tightly coupled to the enclosing class.
Local Class A class declared within a method, constructor, or block. Its scope is limited to that block. ✅ Yes Implementing helper logic within a specific method.
Anonymous Class A class without a name that is declared and instantiated in a single expression. ✅ Yes Creating one-time implementations of interfaces or abstract classes.
Enum Class A special class declared using the enum keyword that represents a fixed set of constants. ❌ No (instances are predefined) Representing predefined values such as days, months, or statuses.
Record Class A special immutable data carrier introduced in Java 16 that automatically generates constructors, accessors, and utility methods. ✅ Yes Modeling immutable data transfer objects (DTOs).
Sealed Class A class declared with the sealed keyword that explicitly restricts which classes can extend or implement it. (Java 17+) Depends on the implementation Creating controlled inheritance hierarchies.

Why Understanding Classes Matters

A deep understanding of Java classes is essential because they form the basis of nearly every feature in the Java language. Concepts such as object creation, inheritance, interfaces, reflection, annotations, serialization, collections, dependency injection, and framework development all depend on a solid understanding of how classes are defined, compiled, loaded, and managed by the JVM.

← Back to Home

Clone this wiki locally