Codectionary / Developer documentation / Java

Classes

Classes in Java are blueprints for creating objects, defining their properties (fields) and behaviors (methods). Java is a strictly object-oriented language where everything is encapsulated within classes. A class serves as a template that specifies what data an object will store and what operations it can perform.

About Java

Java is a statically typed programming language commonly run on the Java Virtual Machine (JVM). It is widely used to organise large applications and build services that can run across different operating systems.

  • Backend services
  • Enterprise software
  • JVM applications
Created by
James Gosling and the team at Sun Microsystems
First released
1995 · public debut
Version / standard
Java 26

Current feature release; some projects use a long-term support release instead.

In the real world

  • Netflix: DGS, its GraphQL services framework
  • LinkedIn: Online services for its AI platform
  • Spotify: The Java API for Voyager vector search

Facts checked 8 September 2026. Links open the sources; examples describe specific products or documented uses.

Syntax

public class ClassName {
  // fields and methods
}

Examples

Create an object

Save as Main.java; compile and run with a JDK.

class Book {
  String title;
  Book(String title) { this.title = title; }
}
public class Main {
  public static void main(String[] args) {
    Book book = new Book("Learning Java");
    System.out.println(book.title);
  }
}

Encapsulate state

Change private state through a method.

class Counter {
  private int value;
  void increment() { value++; }
  int getValue() { return value; }
}
public class Main {
  public static void main(String[] args) {
    Counter counter = new Counter();
    counter.increment();
    System.out.println(counter.getValue());
  }
}

Validate a constructor input

Construct an object only when its required value is present.

class Lesson {
  private final String title;
  Lesson(String title) {
    if (title == null || title.isEmpty()) {
      throw new IllegalArgumentException("Title is required");
    }
    this.title = title;
  }
  String getTitle() { return title; }
}
public class Main {
  public static void main(String[] args) {
    System.out.println(new Lesson("Classes").getTitle());
  }
}

Basic Class

Creating a simple class with fields and methods.

public class Person {
  // Fields
  private String name;
  private int age;
  
  // Constructor
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  
  // Getter methods
  public String getName() {
    return name;
  }
  
  public int getAge() {
    return age;
  }
  
  // Method
  public void introduce() {
    System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
  }
}

// Usage
Person person = new Person("Alice", 25);
person.introduce();

Encapsulation

Using private fields with public getters and setters.

public class BankAccount {
  private String accountNumber;
  private double balance;
  
  public BankAccount(String accountNumber, double initialBalance) {
    this.accountNumber = accountNumber;
    this.balance = initialBalance;
  }
  
  public double getBalance() {
    return balance;
  }
  
  public void deposit(double amount) {
    if (amount > 0) {
      balance += amount;
      System.out.println("Deposited: $" + amount);
    }
  }
  
  public void withdraw(double amount) {
    if (amount > 0 && amount <= balance) {
      balance -= amount;
      System.out.println("Withdrawn: $" + amount);
    } else {
      System.out.println("Insufficient funds");
    }
  }
}

// Usage
BankAccount account = new BankAccount("12345", 1000.0);
account.deposit(500.0);
account.withdraw(200.0);
System.out.println("Balance: $" + account.getBalance());

Inheritance

Creating subclasses that extend parent classes.

public class Animal {
  protected String name;
  
  public Animal(String name) {
    this.name = name;
  }
  
  public void makeSound() {
    System.out.println("Some sound");
  }
}

public class Dog extends Animal {
  private String breed;
  
  public Dog(String name, String breed) {
    super(name);  // Call parent constructor
    this.breed = breed;
  }
  
  @Override
  public void makeSound() {
    System.out.println(name + " says: Woof!");
  }
  
  public void fetch() {
    System.out.println(name + " is fetching the ball");
  }
}

// Usage
Dog dog = new Dog("Buddy", "Golden Retriever");
dog.makeSound();
dog.fetch();

Static Members

Using static fields and methods that belong to the class.

public class Counter {
  private static int count = 0;  // Shared across all instances
  private int instanceId;
  
  public Counter() {
    count++;
    this.instanceId = count;
  }
  
  public static int getCount() {
    return count;
  }
  
  public int getInstanceId() {
    return instanceId;
  }
  
  public static void resetCount() {
    count = 0;
  }
}

// Usage
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

System.out.println("Total instances: " + Counter.getCount());  // 3
System.out.println("c2 ID: " + c2.getInstanceId());  // 2

Best practices

  • Use meaningful class names that describe what the class represents (PascalCase)
  • Keep fields private and provide public getters/setters (encapsulation)
  • Write one class per file, with the filename matching the public class name
  • Use constructors to initialize object state properly
  • Override toString() method for better object debugging
  • Follow the Single Responsibility Principle - each class should have one clear purpose

At a glance

Purpose
General-purpose application development
File extension
.java
Runs in
Java Virtual Machine
Usually used with
JDK and Java libraries

In plain English

A class describes a type of object: the state it stores and the operations it supports. Each instance has its own instance fields.

What you’ll learn

  • Distinguish a class from an object.
  • Initialise objects with a constructor.
  • Keep state behind methods.

Before you start: Variables & Primitive Data Types

Breaking down the syntax

class
Declares a reference type.
field
Stores state belonging to an instance, or to the class when static.
constructor
Initialises a newly created instance.
method
Declares an operation.

How it works

Class definition

Declare fields, constructors and methods.

new

Allocate an instance and invoke a constructor.

Object

Call methods through a reference to that instance.

When should I use this?

Use a class to model related state and behaviour with clear responsibilities. Prefer small cohesive classes over a single class that manages everything.

Common mistakes

Giving a constructor a return type

A declaration with void is a method, even when its name matches the class.

Incorrect

class Book {
  void Book() { }
}

Corrected

class Book {
  Book() { }
}

Compare approaches

  • Class: Encapsulate state and implementation.
  • Interface: Define a contract that classes can implement.
  • Record: Represent a transparent data carrier when appropriate.

Explore deeper

Instance members and static members

Instance fields belong to each object. A static field belongs to the class. A static method has no current instance and cannot directly access instance members without an object reference.

Access control

Make fields private when callers should use operations rather than modify state directly. Public APIs should express what the object does, not expose every implementation detail.

Specifications & further reading

Related Java documentation

Interfaces
An interface defines a contract of methods that implementing classes must provide, without specifying how those methods work internally. Unlike a class, an interface cannot be instantiated directly - it only declares what a class can do, not how. A class uses the 'implements' keyword to fulfill an interface's contract, and a single class can implement multiple interfaces, which is Java's way of achieving a form of multiple inheritance.
Abstract Classes
An abstract class is a class that cannot be instantiated directly and may contain both fully implemented methods and abstract methods (declared without a body, which subclasses must implement). Abstract classes sit between interfaces and regular classes: like an interface, they define a contract; like a regular class, they can hold state (fields) and provide shared, already-implemented behavior.
Constructors
A constructor is a special method that runs automatically when an object is created with 'new', typically used to initialize the object's fields. A constructor shares its name with the class and has no return type, not even void. Java supports constructor overloading, letting a class offer multiple ways to construct an object, and constructor chaining with this(...), where one constructor calls another in the same class.
Access Modifiers
Access modifiers control the visibility of classes, fields, and methods from other parts of a program. Java has four levels: public (accessible from anywhere), protected (accessible within the same package and by subclasses), default/package-private (accessible only within the same package, used when no modifier is written), and private (accessible only within the declaring class itself).