Class and Object in Java
Class
A class is a blueprint or template used to create objects. It defines the properties (variables) and behaviors (methods) that an object will have.
Syntax
class ClassName { // variables // methods }
Example
class Student { String name; int age; void display() { System.out.println("Name: " + name); System.out.println("Age: " + age); } }
Here, Student is a class containing two variables (name, age) and one method (display()).
Object
An object is an instance of a class. It is created using the new keyword and is used to access the variables and methods of a class.
Syntax
ClassName objectName = new ClassName();
Example
class Student { String name; int age; void display() { System.out.println("Name: " + name); System.out.println("Age: " + age); } public static void main(String[] args) { Student s1 = new Student(); s1.name = "Anuradha"; s1.age = 22; s1.display(); } }
Output
Name: Anuradha Age: 22
Difference Between Class and Object
| Class | Object |
|---|---|
| A class is a blueprint or template. | An object is an instance of a class. |
| It does not represent a specific entity by itself. | It represents a specific entity. |
| It defines variables and methods. | It uses the variables and methods of the class. |
A class is declared using the class keyword. | An object is commonly created using new. |
Example: Student | Example: s1 |
Multiple Objects
A single class can be used to create multiple objects.
class Student { String name; void display() { System.out.println(name); } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); s1.name = "Anuradha"; s2.name = "Ram"; s1.display(); s2.display(); } }
Output
Anuradha Ram
Key Points
- Class = Blueprint
- Object = Instance of a class
- Objects are commonly created using the
newkeyword. - A class can create multiple objects.
- Objects can access the variables and methods defined in the class.
Conclusion
Classes and objects are the basic building blocks of Object-Oriented Programming (OOP) in Java. A class defines the structure and behavior, while objects are the actual instances that use that structure and behavior.