1. Introduction
In this blog post, we will learn the difference between Class and Object in Java with an example.
A Class is a blueprint or template from which objects are created. It defines a datatype by bundling data and methods that work on the data into one single unit.
An Object, on the other hand, is an instance of a class. When a class is defined, no memory is allocated until an object is created based on the class.
2. Key Points
1. A Class is a template or blueprint for creating objects.
2. An Object is an instance of a class.
3. A class is a logical entity and doesn't exist in memory until instantiated.
4. An object is a physical entity with a memory allocation.
5. A class defines properties and behaviors for its objects.
3. Differences
Class | Object |
---|---|
Class is a blueprint or a template for creating objects. | Object is an instance of a class. |
Defined with the class keyword. | Created using the new keyword and the constructor of a class. |
It cannot be manipulated directly since it's a concept. | It can be manipulated by calling methods and changing its fields. |
Only one class definition is needed to create multiple objects. | Each object has its own state and identity, even if its properties are identical. |
Static in nature. Once defined, the structure (fields and methods) of a class does not change. | Dynamic in nature. The state of an object (values of its fields) can change over time. |
A class is a logical entity and does not occupy space in memory by itself. | An object occupies space in memory and has a physical presence. |
4. Example
// Step 1: Define a class named 'Book'
class Book {
String title;
String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
void displayInfo() {
System.out.println("Book: " + title + " by " + author);
}
}
public class Main {
public static void main(String[] args) {
// Step 2: Create objects of class 'Book'
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("The Great Gatsby", "F. Scott Fitzgerald");
// Step 3: Use methods on the objects
book1.displayInfo();
book2.displayInfo();
}
}
Output:
Book: 1984 by George Orwell Book: The Great Gatsby by F. Scott Fitzgerald
Explanation:
1. The Book class is defined with a constructor and a method.
2. Two objects (book1 and book2) of the Book class are created, each with its own state (title and author).
3. The displayInfo method is called on both objects, which prints the details of the books.
5. When to use?
- Use a Class when you want to define a new data type that models a concept in your application.
- Create an Object when you need to represent or manipulate an instance of a class in your program.
Comments
Post a Comment
Leave Comment