Java is an object-oriented programming language. Two important concepts in Java are Class and Object.
Let's understand them with a simple example.
- What is a Class?
A class is a blueprint or template used to create objects.
It defines the properties (variables) and behaviors (methods) that its objects can have.
Example:
class Student {
String name;
int age;
void display() {
System.out.println(name);
System.out.println(age);
}
}
Here:
Student is the class name.
name and age are variables.
display() is a method.
The class describes what information and behavior a student object can have.
- What is an Object?
An object is an instance of a class.
We create an object using the new keyword in Java.
Example:
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Arun";
s1.age = 21;
s1.display();
}
}
Output:
Arun
21
Here:
Student is the class.
s1 is the object reference variable.
new Student() creates a new Student object.
s1.name assigns a name.
s1.age assigns an age.
s1.display() calls the method.
- Creating Multiple Objects
We can create multiple objects from the same class. Each object can store different values.
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.name = "Arun";
s1.age = 21;
s2.name = "Priya";
s2.age = 22;
s1.display();
s2.display();
}
}
Output:
Arun
21
Priya
22
Both objects use the same class, but they maintain their own data.
Top comments (0)