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.
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
mainmethod.
// 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
finalfields 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
- Keep classes focused; split one that has unrelated responsibilities.
- Avoid tight coupling through another class’s private implementation.
- Use
finalfor fields that should not be reassigned. - 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
finalfields and no setters
Interview questions
// 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"
Robot r = new Robot("Wall-E"); // new: always creates a new object
List<String> list = List.of("a","b"); // factory: may return cached instance
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"); }
};
// 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
Runnable task = new Runnable() { // anonymous class implementing Runnable
public void run() { System.out.println("running"); }
};
// Lambda would be shorter: () -> System.out.println("running")
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
Further reading
- Constructors: initializing objects with constructors and constructor overloading
- Fields and Instance Variables: managing object state
- Encapsulation: hiding internal state with access modifiers
- Inheritance: subclassing and the extends keyword
- Polymorphism: runtime method dispatch through inheritance
- Oracle: What Is an Object?: official Oracle tutorial on objects and references
- Oracle: Creating Classes: official documentation on class declaration syntax
- Effective Java: Item 1: consider static factory methods instead of constructors
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.
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 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.