✏️ Explanatory Question
Here’s a concise table comparing class and object in Java:
| Aspect | Class | Object |
|---|---|---|
| Definition | A blueprint or template for creating objects. | An instance of a class. |
| Purpose | Defines properties (fields) and behaviors (methods). | Represents a specific entity with data and behavior defined by its class. |
| Memory | Does not occupy memory until an object is created. | Occupies memory when instantiated. |
| Structure | Abstract and logical; a concept. | Concrete and physical; a real entity. |
| Usage | Used to define and encapsulate data and behavior. | Used to access the data and behavior defined by the class. |
| Declaration | Defined using the class keyword. |
Created using the new keyword or other methods. |
| Example in Code | class Car { int speed; void drive() {} } |
Car myCar = new Car(); |
class Car {
int speed; // Property
void drive() { // Behavior
System.out.println("The car is driving.");
}
}
Creating an Object:
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object creation
myCar.speed = 100; // Accessing property
myCar.drive(); // Calling method
}
}
Output:
The car is driving.