Defining Classes in Java — Syntax, Structure & Best Practices
A class is the fundamental building block of Java. Let’s learn how to define one properly.
Basic Class Structure
public class Employee {
// Fields (instance variables)
private String name;
private String department;
private double salary;
// Constructor
public Employee(String name, String department, double salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
// Methods
public String getName() {
return name;
}
public void giveRaise(double percentage) {
this.salary += this.salary * (percentage / 100);
}
public void displayInfo() {
System.out.printf("%s | %s | $%,.2f%n", name, department, salary);
}
}
Anatomy of a Class
[access modifier] class ClassName {
// 1. Fields (state)
// 2. Constructors (initialization)
// 3. Methods (behavior)
// 4. Inner classes, enums (optional)
}
Conventional Ordering
Most Java teams follow this order:
staticconstants and fields- Instance fields
- Constructors
- Public methods
- Private/helper methods
toString(),equals(),hashCode()- Inner classes
Naming Conventions
| Element | Convention | Example |
|---|---|---|
| Class | PascalCase, noun | Employee, BankAccount |
| Interface | PascalCase, adjective/noun | Serializable, PaymentProcessor |
| Method | camelCase, verb | calculatePay(), getName() |
| Field | camelCase, noun | firstName, totalAmount |
| Constant | UPPER_SNAKE | MAX_SALARY, DEFAULT_TAX_RATE |
One Public Class Per File
Java requires the filename to match the public class name:
Employee.java → public class Employee { }
BankAccount.java → public class BankAccount { }
You can have multiple non-public classes in one file, but don’t — it’s bad practice.
The this Keyword
this refers to the current object:
public class Employee {
private String name;
public Employee(String name) {
this.name = name; // this.name = field, name = parameter
}
public Employee getThis() {
return this; // returns the current object
}
}
Method Chaining with this
public class Employee {
private String name;
private String department;
public Employee setName(String name) {
this.name = name;
return this; // enables chaining
}
public Employee setDepartment(String dept) {
this.department = dept;
return this;
}
}
// Usage — fluent API
Employee emp = new Employee()
.setName("Alice")
.setDepartment("Engineering");
Complete Example
public class Product {
// Fields
private String name;
private double price;
private int quantity;
// Constructor
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
// Business logic
public double getTotalValue() {
return price * quantity;
}
public boolean isInStock() {
return quantity > 0;
}
public void sell(int amount) {
if (amount > quantity) {
throw new IllegalArgumentException("Not enough stock");
}
quantity -= amount;
}
// Display
@Override
public String toString() {
return String.format("%s ($%.2f) x %d", name, price, quantity);
}
}
Quick Exercises
- Create a
Rectangleclass withwidthandheight. Add methods forarea(),perimeter(), andisSquare(). - Add method chaining to a
PersonBuilderclass withsetName(),setAge(),setEmail(). - What error do you get if the filename doesn’t match the public class name?
Summary
- Classes define fields (state) + methods (behavior)
- Follow naming conventions: PascalCase for classes, camelCase for methods
- One public class per file, filename must match class name
- Use
thisto refer to the current object - Order: fields → constructors → public methods → private methods
What’s Next?
Now let’s learn how to Create Objects (Instances) using the new keyword and constructors.