What are Classes and Objects? Explain using real-world example

Classes and Objects are fundamental concepts in object-oriented programming (OOP). They help model real-world entities in software by encapsulating data and behavior.

Class:

  • A class is a blueprint or template that defines the structure and behavior (attributes and methods) that the objects of that class will have. It specifies what an object of the class will contain and what it will be able to do.
  • Example: Think of a class as a blueprint for a house. The blueprint defines the structure (rooms, windows, doors) but doesn’t represent an actual house.

Object:

  • An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. The object is what is actually created and used in a program, and it represents a real-world entity.
  • Example: If the class is a blueprint, then an object is an actual house built using that blueprint. Each house (object) can have different properties (color, size) but is built based on the same blueprint (class).

Real-World Example: Library System

  • Class: Book
  • Attributes: title, author, ISBN, publishedYear
  • Methods: borrow(), returnBook(), getDetails()

Java Code:

```java

class Book {

String title;

String author;

String ISBN;

int publishedYear;

  void borrow() {
      System.out.println("The book is borrowed");
  }
void returnBook() {  

System.out.println(“The book is returned”);

}

}

```

  • Object: Specific book instances
  • Example Objects:
    • Book harryPotter = new Book();
    • Book lotr = new Book();

Example Java Code:

```java

public class Library {

public static void main(String[] args) {

Book harryPotter \= new Book(); // Creating an object of class Book

harryPotter.title \= "Harry Potter and the Philosopher's Stone";

harryPotter.author \= "J.K. Rowling";

harryPotter.ISBN \= "978-0747532699";

harryPotter.publishedYear \= 1997;

      harryPotter.borrow();  // Borrowing the book
  }

}

```

Explanation:

- Class (Book): Defines what attributes every book will have (title, author, etc.) and what actions a book can perform (borrow(), returnBook()).

- Objects (harryPotter, lotr): Represent specific books with actual data filled in. Each object can behave according to the methods defined in the class.

Summary

  • Class: A blueprint or template that defines the structure and behavior of objects.
  • Object: An instance of a class that represents a specific entity with its own state and behavior.
  • Real-World Example: A Book class represents the concept of a book, while objects like harryPotter represent specific books in a library system.