1. Introduction
In Java, the concepts of Class and Object are fundamental to its Object-Oriented nature.
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 |
---|---|
Blueprint or template for objects. | An instance of a class. |
Defines properties and behaviors. | Exhibits properties and behaviors defined by the class. |
No memory is allocated for a class itself. | Memory is allocated when an object is created. |
There is only one class definition. | There can be many objects of a class. |
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