Java Classes and Objects: Fields, Constructors, Methods

Learn how Java classes define fields and methods, how constructors initialize objects, and how to create and use instances with the new keyword.

published: reading time: 16 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn how Java classes define state and behavior, how constructors create instances, and how references let code use those objects. Examples cover instance fields, factory methods, nested classes, and common mistakes.

Java Classes and Objects: Fields, Constructors, Methods

Classes define the structure and behavior of reference types. Objects are individual instances of those types.

Introduction

A class defines the fields, methods, and constructors for a type. An object is an instance of that type with its own instance-field values.

The blueprint analogy is useful for one thing: a class describes what its instances can store and do. In Java, class declares a type, and new ClassName() creates an instance by invoking a constructor.

Classes organize Java code and define reference types. For example, String defines string objects, while a Robot class can define robot instances. Writing new Robot("R2-D2") creates an instance and stores its reference in a variable.

Java supports object-oriented programming, but primitive values such as int, boolean, and double are not objects. Reference types and primitive types have different rules and uses.

The examples below cover fields, methods, constructors, and nested classes.

When to use

Use a class when you need to:

  • Model state and behavior that belong together.
  • Create multiple instances with the same structure and different field values.
  • Organize related code into units that can be tested and maintained independently.

Save the following as Robot.java, then run javac Robot.java and java Robot:

public class Robot {
    private final String name;
    private int batteryLevel;

    public Robot(String name) {
        this.name = name;
        this.batteryLevel = 80;
    }

    public void charge() {
        this.batteryLevel = Math.min(100, batteryLevel + 20);
    }

    public String status() {
        return name + ": " + batteryLevel + "%";
    }

    public static void main(String[] args) {
        Robot robot = new Robot("R2-D2");
        System.out.println(robot.status());
        robot.charge();
        System.out.println(robot.status());
    }
}

The output shows one instance before and after charge() runs:

R2-D2: 80%
R2-D2: 100%
// Anonymous class for one-off behavior
Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("Executing task");
    }
};

When an instance adds little

An instance-based type may be unnecessary when:

  • Operations are stateless; static methods may be enough.
  • A record better expresses a fixed set of data components.
  • A primitive represents the value without object identity or behavior.
  • A small application needs only one class with a main method.
// A utility class may be unnecessary for a one-off operation.
class StringUtils {
    public static String capitalize(String s) {
        return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }
}
// For a one-off use, call the operation where it is needed.

Class anatomy

classDiagram
    class Robot {
        -String name
        -int batteryLevel
        +Robot(String name)
        +charge() void
        +status() String
        +main(String[]) void
    }

Failure scenarios

1. Uninitialized Reference

An instance reference field with no initializer starts as null. Dereferencing a null reference, such as by calling one of its methods, throws NullPointerException. A local variable is different: Java requires it to be assigned before it is read.

Null fields can result when a constructor leaves them unset or when a conditional assignment is skipped. The compiler permits a field to remain null because null is a valid reference value; it checks that local variables are definitely assigned before use.

Robot robot = null;
robot.charge(); // NullPointerException: robot is null

// Fix: always initialize before use
robot = new Robot("Wall-E");

2. Mutable Shared State via References

Aliasing happens when two reference variables point to the same object. Assigning one reference to another does not copy the object. A mutation through one reference changes the shared instance; in concurrent code, synchronization may also be needed for safe access and visibility.

This matters when a method exposes a mutable collection or stores a reference supplied by a caller. A defensive copy can prevent outside code from changing the collection structure owned by the class.

List<String> list1 = new ArrayList<>();
List<String> alias = list1; // Both references point to the same list
alias.add("item");         // list1 now contains "item" too

// Fix: create independent copies
List<String> copy = new ArrayList<>(list1);

3. Forgetting new

For ordinary object creation, Java uses new to create an instance and invoke its constructor. Writing Robot("Test") without new is not a constructor call; the compiler treats it as a method call and reports an error if no such method exists. Inside a constructor, this(...) or super(...) can invoke another constructor.

Factory methods like String.valueOf(42) are static methods that return a value. Call them by method name. A bare ClassName(args) expression is not a constructor call in Java.

String s = String.valueOf(42);  // Factory method: correct
Robot r = Robot("Test");        // Compile error: forgot new
Robot r = new Robot("Test");     // Correct

Trade-off table

Approach Use Case Drawback
Concrete class Full control over behavior and state More boilerplate
Abstract class Shared base with partial implementation Single inheritance limit
Interface Multiple contracts without instance fields No per-instance state
Record (Java 16+) Shallowly immutable data carrier Mutable components need care
Enum Fixed set of constants Not extendable at runtime

Code examples

Static factory methods

Factory methods are named static methods that return a value. For example, createVacuumBot("Roomba") says more about intent than new Robot("Roomba").

Factory methods can return existing instances instead of creating new ones every time. Integer.valueOf(42) returns an instance from the required cache range, which includes -128 through 127. A factory method may also return a subtype, reuse an instance, or return null if its contract allows that. A constructor invocation initializes the newly created instance; it cannot return an existing object.

Factory methods are ordinary static methods, not constructor overloads. A subclass can call an accessible static method inherited from its parent, but it may need its own factory to create and return a subtype.

public class Robot {
    private final String name;

    private Robot(String name) {  // Private constructor
        this.name = name;
    }

    // Static factory method instead of public constructor
    public static Robot createVacuumBot(String name) {
        return new Robot(name);
    }

    public static Robot createSecurityBot(String name) {
        Robot bot = new Robot(name);
        // Security bot specific setup
        return bot;
    }
}

// Usage
Robot vac = Robot.createVacuumBot("Roomba");
Robot sec = Robot.createSecurityBot("Guard");

Nested classes

Java lets you declare a class inside another class. The enclosing class is the outer class; the declaration inside it is a nested class. This can keep closely related types together.

Java has four kinds of nested classes:

Kind Keyword Access to Outer Instance Instantiation
Static nested class static No new Outer.Inner()
Member inner class (none) Yes: implicit Outer.this outer.new Inner()
Local inner class (none, inside method) Yes: from enclosing method Inside that method only
Anonymous class (no name) Inherits or implements one type Inline in expression

Static nested classes have no implicit reference to an outer instance. They cannot access outer instance fields directly, but they can access static members. Use one when a class belongs conceptually with an outer type but does not need an outer object.

Non-static member inner classes hold an implicit reference to an outer instance, so they can access its members. The outer.new Inner() syntax reflects that relationship. If an inner instance remains reachable, it can keep its outer instance reachable too.

Local inner classes are declared inside a method body and can access effectively final local variables from that method. Anonymous classes have no name and are defined and instantiated in one expression. Lambdas are a shorter option when the target is a functional interface.

public class Outer {
    private String outerField = "outer";

    public class Inner {
        private String innerField = "inner";
        public void accessOuter() {
            System.out.println(outerField);  // Can access outer class field
        }
    }
}

// Instantiate inner class via outer instance
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

Observability checklist

  • Fields are private with controlled access via getters/setters
  • Constructor validates required parameters
  • Immutable classes use final fields and no setters
  • Static fields documented with their purpose
  • Thread-safe design for shared instances

Security notes

Private fields keep implementation details out of the public API. When a class accepts or returns a mutable collection, copy it if callers should not share ownership of that collection. Immutable values reduce shared mutable state, and constructors or setters should reject values that break the class’s invariants.

import java.util.List;

public class User {
    private final List<String> roles;

    public User(List<String> roles) {
        this.roles = List.copyOf(roles);
    }

    public List<String> getRoles() {
        return roles; // Unmodifiable snapshot of the collection structure
    }
}

Pitfalls

  1. Keep classes focused; split one that has unrelated responsibilities.
  2. Avoid tight coupling through another class’s private implementation.
  3. Use final for fields that should not be reassigned.
  4. Remember that reassigning a parameter does not change the caller’s variable.
// Bad: modifying parameter
public void process(User user) {
    user = new User();  // This only changes local copy, not the caller's reference
}

// Good: operate on the object, don't reassign
public void process(User user) {
    user.updateStatus("active");  // Call methods on the object
}

Quick recap

  • Class = blueprint defining state (fields) and behavior (methods)
  • Object = instance created from a class via new
  • Reference = value that refers to an object; Java does not specify it as a raw memory address
  • Encapsulation = keep fields private, expose via methods
  • Immutability = use final fields and no setters

Interview questions

1. What is the difference between a class and an object?
A class is a blueprint or template that defines the structure (fields) and behavior (methods) that objects of that type will have. An object is a concrete instance created from that blueprint, occupying its own memory with actual values for the fields.
// Class: the blueprint
public class Robot {
    private String name;
    public Robot(String name) { this.name = name; }
    public String getName() { return name; }
}

// Object: a real instance created from the blueprint
Robot bot = new Robot("R2-D2");  // new triggers constructor
String name = bot.getName();      // "R2-D2"
2. Can a class have multiple constructors?
Yes. Java supports constructor overloading: multiple constructors with different parameter lists. This allows flexible object creation with different initial states.
3. What is the default value of an object reference field?
An instance field of a reference type defaults to `null`; primitive fields have type-specific defaults. Local variables are not default-initialized and must be assigned before they are read.
4. What is the difference between `new` and factory methods?
`new` always creates a fresh instance via a constructor. Factory methods (like `List.of()` or `Path.of()`) can return cached instances, existing objects, or subclasses: the caller receives an instance without knowing or caring about the concrete type.
Robot r = new Robot("Wall-E");       // new: always creates a new object
List<String> list = List.of("a","b"); // factory: may return cached instance
5. When should you use a record instead of a class?
Use a record when the main purpose of a type is to model a fixed set of values, such as a result or data-transfer object. Records provide component accessors and generated implementations of `equals`, `hashCode`, and `toString`. Their fields are final, but a component can still refer to a mutable object.
6. What happens when you try to instantiate an interface directly in Java?
Compilation error: interfaces cannot be instantiated with `new`. Interfaces are abstract contracts and require a concrete implementation class.
Runnable r = new Runnable();  // Compile error: Runnable is abstract; cannot be instantiated
Runnable r = new Runnable() { // Correct: implement it with an anonymous class
    public void run() { System.out.println("task"); }
};
7. Can a class have both instance methods and static methods? Explain the difference.
Yes: instance methods require an object (via new) and operate on instance state. Static methods belong to the class itself, not instances: called via ClassName.method(). Static methods cannot access instance fields directly without an object reference.
8. What is the difference between a nested class and an inner class in Java?
A static nested class is independent of any outer instance: instantiate it with `new OuterClass.InnerClass()`. A non-static inner class holds an implicit reference to its outer instance and can access outer class members directly. Inner classes require an outer instance to create; static nested classes do not.
// Static nested: no outer instance needed
Outer.StaticNested n = new Outer.StaticNested();

// Non-static inner: requires an outer instance
Outer outer = new Outer();
Outer.Inner i = outer.new Inner();  // note the outer.new syntax
9. Why should mutable objects stored as fields be defensive-copied in constructors and getters?
A defensive copy prevents a caller from changing the collection structure owned by your class. A shallow copy still shares mutable elements, so copy those too if they must be isolated.
10. What is method signature and does it include the return type?
Method signature includes method name and parameter types (e.g., doSomething(String, int)). Return type is NOT part of the method signature in Java. Two methods with same name and params but different return types cause compilation error.
11. What is the purpose of the `static` keyword on a nested class?
Makes the nested class independent of any outer class instance. Static nested class cannot access outer class instance fields or methods directly. Useful when nested class doesn't need to reference outer class instances.
12. What is an anonymous class and when would you use one?
An anonymous class is a local class with no name, defined and instantiated in a single expression. Useful for one-off interface implementations or extending classes on the fly.
Runnable task = new Runnable() {  // anonymous class implementing Runnable
    public void run() { System.out.println("running"); }
};
// Lambda would be shorter: () -> System.out.println("running")
13. Can a class be declared as both `final` and `abstract`?
No: these are mutually exclusive modifiers. abstract means the class must be subclassed; final means the class cannot be subclassed. Compilation error results from this combination.
14. What is the difference between member nested class and local inner class?
Member inner class is declared at class level (as a member of the outer class). Local inner class is declared inside a method body. Local inner class can access effectively final local variables of the enclosing method.
15. What happens when a class has no explicit constructor definition?
Java compiler provides a default no-arg constructor automatically. This default constructor initializes all instance fields to default values (0, false, null). Once you define any constructor, the default is no longer provided.
16. What is the relationship between `class` and `interface` for multiple inheritance?
Java class supports single inheritance only (one extends clause). Class can implement multiple interfaces (implements clause accepts comma-separated list). Interface can extend multiple interfaces (allows contract composition without state inheritance).
17. When is it appropriate to use `var` (local variable type inference) in Java 10+?
Useful for long generic type names or complex generic chains. Cannot use var for fields, method parameters, or constructor parameters. Must initialize var on declaration: compiler infers exact type from initializer.
18. What is the purpose of a private constructor in a class?
A private constructor prevents callers outside the class from invoking it directly. A singleton often uses one, but the class must also control access to the instance; the simple lazy example below is not thread-safe. A private constructor can also require callers to use a factory method.
public class DatabaseConnection {
    private static DatabaseConnection instance;
    private DatabaseConnection() {}  // private: no external new

    public static DatabaseConnection getInstance() {
        if (instance == null) instance = new DatabaseConnection();
        return instance;
    }
}
DatabaseConnection db = DatabaseConnection.getInstance();  // correct
DatabaseConnection db2 = new DatabaseConnection();           // compile error
19. What is the difference between an object reference and a primitive variable?
Primitive variables hold values such as an integer or boolean. Reference variables refer to objects. The Java language does not specify references as raw memory addresses or require local variables to occupy a particular physical location. Fields are default-initialized; local variables must be assigned before use.
20. What is the diamond problem and how does Java handle multiple inheritance?
Java classes can extend one class, but they can implement multiple interfaces. If two interfaces provide conflicting default methods, the implementing class must resolve the conflict, usually by overriding the method.

Further reading

Conclusion

Classes define reference types; objects are their instances. Use new for ordinary instance creation, then call methods through a reference to that instance.

Reference variables refer to objects, but the Java language does not specify them as raw memory addresses. Multiple references can refer to the same object, so a mutation through one reference is visible through the others. Private fields and defensive copies help control access to mutable state.

Static factory methods such as List.of(), Path.of(), and Optional.of() provide named ways to obtain values. Their contracts determine whether they return a new instance, a reused instance, or a subtype. Constructors initialize the instance created for them.

Anonymous classes and lambdas are useful for one-off behavior. Static nested, member inner, local, and anonymous classes each have different relationships to their enclosing code.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals