What Is a Class in Java? Blueprint, Fields, Methods
A class in Java is a blueprint that defines the structure and behaviour of objects. It declares what data (fields) each object holds and what it can do (methods). No computation happens until you create an object from the class using new.
A minimal class
public class Person {
// Fields (instance variables)
String name;
int age;
// Method
void greet() {
System.out.println("Hi, I'm " + name);
}
}
This class defines what every Person object looks like — each has a name and an age — and what it can do: greet().
Creating objects from a class
Person p1 = new Person();
p1.name = "Ada";
p1.age = 36;
p1.greet(); // Hi, I'm Ada
Person p2 = new Person();
p2.name = "Grace";
p2.greet(); // Hi, I'm Grace
p1 and p2 are two independent objects, each with their own copy of name and age. The class is the blueprint; the objects are concrete instances of it.
Access modifiers
| Modifier | Visible to |
|---|---|
public | Everyone |
protected | Same package + subclasses |
| (none / package-private) | Same package only |
private | This class only |
Good encapsulation practice: make fields private and expose them via public getter/setter methods or immutable value-object constructors.
Static vs instance members
public class Counter {
private static int total = 0; // shared by all instances
private int count = 0; // unique to each instance
public void increment() {
count++;
total++;
}
public static int getTotal() { return total; }
public int getCount() { return count; }
}
Modern alternative: records (Java 16+)
For classes that are just data carriers, Java 16 introduced records — they generate constructor, getters, equals, hashCode and toString automatically:
public record Point(int x, int y) {}
Point p = new Point(3, 4);
System.out.println(p.x()); // 3
System.out.println(p); // Point[x=3, y=4]
One class per file (mostly)
By convention, each public class lives in its own .java file with a matching filename. public class Person lives in Person.java. Non-public helper classes can share a file, but this is uncommon outside of small inner class patterns.