1. Class & Object in Java
The foundation of Object-Oriented Programming: blueprints (classes) and real instances (objects).
What is a Class in Java?
English Definition
A class is a blueprint or template for creating objects. It defines fields (state) and methods (behavior) that every object created from it will have.
Hinglish Explanation
Class ek blueprint ya template hoti hai jiske through objects create kiye jaate hain. Hum ek hi class se multiple objects bana sakte hain.
Student.java — Defining a Class
class Student {
int rollno;
String name;
void display() {
System.out.println(rollno);
System.out.println(name);
}
}
Breakdown & Explanation
Studentis a class (the blueprint).rollnoandnameare instance variables (each object gets its own copy).display()is a method that prints the student's details.- We can create multiple objects from the same
Studentclass.
What is an Object in Java?
English Definition
An object is an instance of a class. It occupies memory when created with the
new keyword and has both state (fields) and behavior (methods).
Hinglish Explanation
Object, class ka instance hota hai. Jab hum
new Student() likhte hain, tab actual object memory mein create hota hai.
Student.java — Creating & Using an Object
class Student {
int rollno;
String name;
void display() {
System.out.println(rollno + " " + name);
}
public static void main(String args[]) {
Student s1 = new Student();
s1.rollno = 101;
s1.name = "Rahul";
s1.display();
}
}
Console Output101 Rahul
Line-by-Line Meaning
Student→ Class (Blueprint)new Student()→ Creates an object in memorys1→ Reference variable that refers to the objectrollno&name→ Object's statedisplay()→ Object's behavior
Interactive Object Creator
Create your own Student object below to see how state & behavior work:
s1 = new Student() → Ready