Defining Your Own Classes in Java: Fields, Constructors and Methods
Write your first real Java class: an Employee with private fields, a constructor and methods. Covers multiple classes and source files, how javac finds dependencies, constructor rules, var for local variables, handling null with Objects.requireNonNull, and implicit vs. explicit parameters and this.
kvi5hnuCode Sprout team member12 min readOn this page
Up to now, every class you wrote was little more than a container for main. Real programs look different. Most of their classes hold data of their own (instance fields) plus the operations on that data (methods), and most of them have no main at all. One class with main starts the program; the others do the actual work.
This article builds a small Employee class, the kind a staff-records or payroll tool would need, and then goes through it piece by piece.
The Shape of a Class
The simplest form of a class definition is:
class ClassName {
field
field
...
constructor
constructor
...
method
method
...
}
Fields, constructors and methods can appear in any order, but this order (fields, then constructors, then methods) is the common convention.
Here's a very simplified Employee class:
class Employee {
// instance fields
private String name;
private double salary;
private LocalDate startDate;
// constructor
public Employee(String n, double s, int year, int month, int day) {
name = n;
salary = s;
startDate = LocalDate.of(year, month, day);
}
// methods
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public LocalDate getStartDate() {
return startDate;
}
public void giveRaise(double pct) {
double raise = salary * pct / 100;
salary += raise;
}
}

The Class in Action
The program below fills an array with three employees, gives every one of them a 4% raise, and prints the result. The example below puts both classes in one file. The class with main is public, and its name matches the file name.
import java.time.LocalDate;
public class Solution {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Priya Nair", 68000, 2016, 4, 11);
staff[1] = new Employee("Omar Haddad", 52000, 2019, 9, 2);
staff[2] = new Employee("Lena Fischer", 46000, 2021, 6, 21);
for (Employee e : staff) {
e.giveRaise(4);
}
for (Employee e : staff) {
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()
+ ",startDate=" + e.getStartDate());
}
}
}
class Employee {
private String name;
private double salary;
private LocalDate startDate;
public Employee(String n, double s, int year, int month, int day) {
name = n;
salary = s;
startDate = LocalDate.of(year, month, day);
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public LocalDate getStartDate() {
return startDate;
}
public void giveRaise(double pct) {
double raise = salary * pct / 100;
salary += raise;
}
}
name=Priya Nair,salary=70720.0,startDate=2016-04-11
name=Omar Haddad,salary=54080.0,startDate=2019-09-02
name=Lena Fischer,salary=47840.0,startDate=2021-06-21
A few things to note:
new Employee[3]creates an array of threenullreferences. Thenew Employee(...)calls create the actual objects.- The loops use the for-each form over the array of objects.
erefers to eachEmployeein turn, ande.giveRaise(4)changes that object's salary. - The file contains two classes. A source file can contain only one
publicclass, and the file must be named after it (hereSolution.java; in a typical project, something likeStaffDemo.java). It can contain any number of non-public classes. - Compiling produces one
.classfile per class:Solution.classandEmployee.class. You run the program by naming the class that containsmain:java Solution.
Multiple Source Files
The usual habit is one class per source file, say Employee.java and StaffDemo.java. Either of these commands then compiles the program:
javac Employee.java StaffDemo.java # list every file
javac StaffDemo.java # name only the class with main
The second form works because javac resolves dependencies on its own. While compiling StaffDemo.java it meets the type Employee, searches for Employee.class, and, if that file is missing or older than Employee.java, compiles the source too. So a simple dependency check, the job a make tool usually does, comes for free.
For real projects, you'll use a build tool (Maven or Gradle) or an IDE, which manage compilation of hundreds of files, dependencies and tests. And since Java 22, the java launcher can run a multi-file program directly from source: java StaffDemo.java compiles the other source files it references on the fly.
Dissecting the Employee Class
Methods and public
The class has one constructor and four methods:
public Employee(String n, double s, int year, int month, int day)
public String getName()
public double getSalary()
public LocalDate getStartDate()
public void giveRaise(double pct)
All are tagged public: any method in any class can call them. (Java has four access levels; you'll meet them all in this part and the next.)
Private instance fields
private String name;
private double salary;
private LocalDate startDate;
private means that only the methods of the Employee class itself can access these fields. No outside code can read or write them directly.
Notice that two fields, name and startDate, have class types. They hold references to String and LocalDate objects. That's very common: objects are typically built from other objects.
Instance field defaults
Unlike local variables, instance fields are initialized automatically if the constructor doesn't set them: numbers to 0, boolean to false, and object references to null. Relying on this is often a sign of sloppy code, though; more on field initialization in the constructors article.
First Steps with Constructors
public Employee(String n, double s, int year, int month, int day) {
name = n;
salary = s;
startDate = LocalDate.of(year, month, day);
}
A constructor is named exactly like its class. Its job is to put a freshly created object into a valid starting state. The expression
new Employee("Dana Whitfield", 93000, 1998, 7, 6)
creates an object and runs the constructor on it, which leaves the fields holding
name = "Dana Whitfield";
salary = 93000;
startDate = LocalDate.of(1998, 7, 6); // 6 July 1998
You can't treat a constructor like a normal method and call it again later on an existing object. It only runs as part of new:
dana.Employee("Dana Whitfield", 99000, 1998, 7, 6); // compile-time error
The rules so far:
| Rule | What it means |
|---|---|
| Name | Always identical to the class name |
| Return type | None, and you don't write void either |
| Parameters | Any number, including none |
| Overloading | A class may declare several constructors with different parameter lists |
| Invocation | Only through new (or from another constructor, covered later) |
Declaring Local Variables with var
Inside methods you can declare local variables with var when the type is obvious from the initializer:
Employee omar = new Employee("Omar Haddad", 52000, 2019, 9, 2);
var omar = new Employee("Omar Haddad", 52000, 2019, 9, 2); // same
This avoids repeating Employee. var works only for local variables. Fields, method parameters and return types always need an explicit type.
A reasonable guideline is to use var when the type is evident from the right-hand side (new Employee(...), LocalDate.of(...)), and to spell out the type when it isn't, or for numbers, where var x = 0 versus 0L versus 0.0 silently changes the type. The OpenJDK project publishes a style guide for local variable type inference (search for "LVTI style guide") with sensible recommendations.
Working with null References
An object variable may hold null, meaning "no object". That's handy for "unknown" or "not yet set" values, but you must be careful: calling a method on null throws a NullPointerException:
LocalDate rightNow = null;
String s = rightNow.toString(); // NullPointerException
If the program doesn't catch it, it terminates. Programs usually don't catch these exceptions; programmers are expected not to cause them.
Decide which fields may be null
When you design a class, decide which fields are allowed to be null. In Employee, name and startDate shouldn't be. (salary is a primitive double and can never be null.) startDate is safe because the constructor always creates a LocalDate. But name would be null if someone passed null for n.
There are two approaches.
Permissive: replace a null argument with a sensible default:
if (n == null) name = "unknown"; else name = n;
// or, using java.util.Objects:
name = Objects.requireNonNullElse(n, "unknown");
Strict: refuse a null argument immediately:
public Employee(String n, double s, int year, int month, int day) {
name = Objects.requireNonNull(n, "The name cannot be null");
...
}
Constructing an Employee with a null name now throws a NullPointerException immediately, with your message. That may not sound like an improvement, but:
- The exception report describes the problem.
- It pinpoints where the bad value came in.
Otherwise, the NullPointerException would occur later, somewhere else, when name is used, and tracing it back to the faulty constructor call would be hard. This "fail fast" style is generally preferred. Whenever a parameter is an object reference, ask yourself whether you really mean to allow an absent value. If not, reject null.
The java.util.Objects helpers for this:
| Method | Behaviour |
|---|---|
requireNonNull(obj) / requireNonNull(obj, message) 7 | returns obj, or throws NullPointerException (with the message) if it's null |
requireNonNull(obj, messageSupplier) 8 | same, but builds the message only when needed (suppliers are covered with lambdas) |
requireNonNullElse(obj, defaultObj) 9 | returns obj, or defaultObj if obj is null |
requireNonNullElseGet(obj, defaultSupplier) 9 | same, but computes the default only when needed |
(Java has no built-in "non-null type" yet. Many projects use annotations like @NonNull/@Nullable (for example JSpecify) together with static analysis tools to catch nulls at compile time. Absent values that are expected are often modeled with Optional, which is covered later.)
The Object a Method Runs On: this and Explicit Parameters
An instance method always works on some particular object. Take this method:
public void giveRaise(double pct) {
double raise = salary * pct / 100;
salary += raise;
}
and the call:
lead.giveRaise(4);
It increases lead's salary by 4%. You can picture the call as running
double raise = lead.salary * 4 / 100;
lead.salary += raise;

So giveRaise receives two inputs, not one:
- The implicit argument is the object written before the dot (
lead). You'll also see it called the receiver or target of the call. - The explicit argument is what appears between the parentheses (
4).
The method declares a parameter variable for the explicit argument (double pct), but not for the implicit one. Every method has an implicit parameter named this, which refers to the implicit argument. You can write the method as:
public void giveRaise(double pct) {
double raise = this.salary * pct / 100;
this.salary += raise;
}
Some programmers prefer this style because it clearly distinguishes instance fields from local variables. It becomes necessary when a parameter has the same name as a field, a common idiom you'll see in the constructors article:
public Employee(String name, double salary) {
this.name = name; // field = parameter
this.salary = salary;
}
Common questions
Should every class be in its own file? Every public top-level class must be in a file of the same name. For other classes it is a convention, not a rule. Most teams still put one top-level class in each file, so classes are easy to find, and use nested classes for small helpers that belong to one class.
What is the difference between a field and a local variable?
A field belongs to an object (or to the class, if it is static), lives as long as the object does, and gets a default value. A local variable belongs to one method call, exists only while its block runs, and must be assigned before it is read.
Do I need to write this. in front of every field?
No. Inside an instance method, salary already means this.salary, unless a parameter or local variable with the same name shadows it. Use this. when a parameter has the same name as the field, which is common in constructors and setters. Elsewhere it's a matter of style.
Should a constructor call other methods?
It may call private or final helper methods. Avoid calling methods that a subclass could override. The override would run before the subclass's own fields are initialised, which is a classic source of bugs (covered in the inheritance part).
What does Objects.requireNonNull give me over letting the NPE happen later?
It fails immediately, at the point where the bad value enters the object, with a clear message. A later NullPointerException points to the place where the field was used, which might be far away and much later. That makes it hard to find the caller that passed null.
Summary
- A class contains instance fields, constructors and methods. A program combines several classes; one has
main. - A source file can contain only one
publicclass, named like the file;javacproduces one.classfile per class and compiles referenced source files automatically. - Make instance fields
private; expose behaviour throughpublicmethods. - Constructors have the class's name, no return type, can be overloaded, and run only with
new. Don't redeclare fields as local variables inside them. vardeclares local variables with an inferred type; fields and parameters need explicit types.- Decide which fields may be
null. UseObjects.requireNonNullto fail fast, orrequireNonNullElseto substitute a default. - Every method has an implicit parameter
this(the object it's called on) in addition to its explicit parameters.
Practice Questions
A file named Payroll.java contains public class Employee {…} and class Payroll { public static void main… }. Why won't it compile, and how do you fix it?
The public class must have the same name as the file. Either rename the file to Employee.java (and run java Payroll), make Payroll the public class instead, or put each class in its own file.
What's wrong with this constructor? public Employee(String n, double s) { String name = n; double salary = s; }
It declares new local variables name and salary, which shadow the fields. The fields themselves are never set (they stay null and 0.0). Write name = n; salary = s; (or this.name = n;).
In omar.giveRaise(10), what are the implicit and explicit arguments, and how does the method refer to each?
The implicit argument is the object omar, referred to as this (or implicitly, through unqualified field names like salary). The explicit argument is 10, bound to the parameter pct.
Can you write dana.Employee("Dana", 1000, 2000, 1, 1); to reset an object's fields?
No. A constructor can only be invoked with new to create a new object. To change an existing object, provide mutator methods.
Why is Objects.requireNonNull(n, "The name cannot be null") in the constructor better than letting a null name through?
It fails immediately, at the place where the bad value enters, with a clear message. Otherwise the NullPointerException happens later, wherever name is first used, far from the actual mistake.
Where can var be used? Can you declare a field as private var count = 0;?
Only for local variables (including for-loop and try-with-resources variables) with an initializer. Fields, parameters and return types must be declared with explicit types, so private var count = 0; is a compile error.
Previous: Using Predefined Classes in Java: Objects, Object Variables and LocalDate
Next: Java Encapsulation: Accessors, Mutators, private Methods and final Fields
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.