What is a class in Java?
Solution and explanation
What it is
A class is a blueprint or template that describes what an object will contain (fields/state) and what it can do (methods/behaviour). The class itself is just a definition; objects are the real instances created from it.
Analogy: the architect's plan of a flat is the class. The 200 flats built from that plan in a society are objects. Every flat has the same structure (rooms, doors) but different values (owner name, paint colour).
Structure of a class
public class Car { // class declaration
// 1. Fields (state)
private String brand;
private String model;
private int speed;
// 2. Constructor (initialises a new object)
public Car(String brand, String model) {
this.brand = brand;
this.model = model;
}
// 3. Methods (behaviour)
public void accelerate(int amount) {
speed += amount;
}
public String describe() {
return brand + " " + model + " at " + speed + " km/h";
}
}
Using the class
Car baleno = new Car("Maruti", "Baleno");
Car creta = new Car("Hyundai", "Creta");
baleno.accelerate(60);
System.out.println(baleno.describe()); // Maruti Baleno at 60 km/h
System.out.println(creta.describe()); // Hyundai Creta at 0 km/h
What a class can contain
- Fields (instance and static variables)
- Constructors
- Methods (instance and static)
- Blocks (instance initializer
{ }, static blockstatic { }) - Nested classes, interfaces, enums and records
Rules
- A
.javafile can have only one public top-level class, and the file name must match it (Car.java). - Class names use PascalCase by convention.
- Every class implicitly extends
java.lang.Object.
