Write a difference between class and a object
Single Choice
Views 60
Answer:
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(); |
Example
Defining a Class
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.
Key Takeaway
- A class is a blueprint for creating objects, while an object is an actual instance of a class, containing real data and behavior.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.