Classes and Objects in Java
Let's explore the fundamentals of object-oriented programming — Classes and Objects — in Java, with clear explanations and code examples.
✅ What is a Class in Java?
A class is a blueprint or template that defines the structure and behavior (data and methods) that the objects created from it will have.
πΉ Think of a class as:
-
A design for creating objects.
-
It contains fields (variables) and methods (functions).
πΈ Syntax:
✅ What is an Object in Java?
An object is an instance of a class.
-
It represents a real-world entity.
-
Each object has its own state (fields) and can perform actions (methods).
πΈ Example:
If Car
is a class, then myCar
and yourCar
are objects of that class.
✅ Java Program: Creating and Using a Class and Object
✅ Output:
πΈ Key Terminologies
Term | Description |
---|---|
class | Keyword to define a class |
new | Keyword used to create an object |
Constructor | Special method used to initialize objects (explained below) |
Dot operator . | Used to access members of an object (e.g., object.method() ) |
✅ Constructor in Java
A constructor is a special method that is automatically called when an object is created.
πΉ Example:
Output:
✅ Summary
Feature | Description |
---|---|
Class | Blueprint that defines variables and methods |
Object | Instance of a class |
Constructor | Initializes object when created |
new keyword | Used to create object |
Dot . operator | Access fields and methods of object |
Comments
Post a Comment