A class is a blueprint; an object is a specific thing built from that blueprint. This is the foundation everything else in Java builds on.
Defining a class
public class Student {
// fields (state)
String name;
int age;
// constructor - runs when you create a new Student
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// method (behavior)
public void introduce() {
System.out.println("Hi, I am " + name + ", age " + age);
}
}
Creating objects
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Riya", 21);
Student s2 = new Student("Aman", 22);
s1.introduce(); // Hi, I am Riya, age 21
s2.introduce(); // Hi, I am Aman, age 22
}
}
Why "this"?
this.name refers to the field on the object itself, distinguishing it from the constructor parameter name - without this, name = name would just assign the parameter to itself and do nothing useful.
Encapsulation: private fields, public methods
In real code, fields are usually private and accessed through public "getter" and "setter" methods - this lets the class control how its data is read and changed:
public class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}