Definition
📌 Classes & Objects
A class is a blueprint for creating objects — it defines the data (fields) and behavior (methods) that its objects will have.
Syntax
syntax
class ClassName {
fields;
ClassName(parameters) { ... } // constructor
returnType method() { ... }
}
ClassName obj = new ClassName(args);Example
java
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void introduce() {
System.out.println("Hi, I'm " + name + ", age " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Aisha", 21);
s1.introduce();
}
}Output
outputHi, I'm Aisha, age 21
Important Points
- A constructor has the same name as the class and runs automatically when you create an object with
new. thisrefers to the current object — useful when a parameter shares a name with a field.- Fields hold an object's state; methods define its behavior.
- Multiple objects from the same class each have their own independent copy of the fields.
Common Mistakes
- Forgetting to use
this.field = parameter;when the parameter and field share the same name. - Confusing a class (the blueprint) with an object (an actual instance).
- Making all fields
publicinstead of using getters/setters — this breaks encapsulation, a core OOP principle.
Interview Tip
🎯 Before your interview
Be ready to define encapsulation in one sentence: bundling data and the methods that operate on it, while restricting direct access to that data.
