In Java, Classes and Objects are the fundamental building blocks of Object-Oriented Programming (OOP). Think of it like the relationship between a blueprint and a house.
1. What is a Class?
A Class is a template or a "blueprint" for creating objects. It defines what data the object will hold and what it can do. It doesn't occupy memory space itself; it just describes the structure.
A class consists of two main components:
Fields (Attributes): Variables that represent the state/properties (e.g., color, model).
Methods (Behaviors): Functions that represent what the object can do (e.g., accelerate, brake).
2. What is an Object?
An Object is an "instance" of a class. When you create an object, you are bringing that blueprint to life. Unlike a class, an object occupies memory.
You can create multiple objects from a single class. For example, if the class is Car, the objects could be myTesla and yourFord.
3. The Code Example
Here is how you define a class and then create an object from it in Java:
4. Key Differences
| Feature | Class | Object |
|---|---|---|
| Definition | A template for creating objects. | An instance of a class. |
| Memory | Does not allocate memory when defined. | Allocates memory when created. |
| Existence | Logical entity. | Physical entity. |
| How many? | Declared only once. | Multiple objects can be created from one class. |
5. The new Keyword
To create an object in Java, we use the new keyword. It performs three vital steps:
Declaration:
Dog myDogassociates a variable name with an object type.Instantiation: The
newkeyword creates the object.Initialization: The
newkeyword is followed by a call to a Constructor, which sets up the initial state of the object.