Mark As Completed Discussion

Encapsulation

In object-oriented programming (OOP), encapsulation is the concept of bundling data (attributes) and methods (behaviors) into a single unit called a class. It allows us to hide the internal implementation details of a class and only expose the necessary information to the outside world.

Encapsulation is achieved by using access modifiers such as private, protected, and public to control access to the members of a class. By making certain data and methods private, we can prevent direct access to them from outside the class.

Encapsulation provides several benefits including:

  • Data Hiding: Encapsulation allows us to hide the internal data of a class, preventing unauthorized access and modification. This helps in maintaining the integrity and consistency of the data.

  • Abstraction: Encapsulation provides a way to represent complex systems by abstracting away the internal details and exposing only the necessary interfaces. This simplifies the usage and understanding of the class.

To demonstrate encapsulation, let's consider the example of a Book class. The Book class has private attributes such as title, author, and numOfPages, along with getter and setter methods to access and modify these attributes. The printDetails() method is used to print the details of the book:

TEXT/X-JAVA
1public class Book {
2    private String title;
3    private String author;
4    private int numOfPages;
5
6    public Book(String title, String author, int numOfPages) {
7        this.title = title;
8        this.author = author;
9        this.numOfPages = numOfPages;
10    }
11
12    public String getTitle() {
13        return title;
14    }
15
16    public void setTitle(String title) {
17        this.title = title;
18    }
19
20    public String getAuthor() {
21        return author;
22    }
23
24    public void setAuthor(String author) {
25        this.author = author;
26    }
27
28    public int getNumOfPages() {
29        return numOfPages;
30    }
31
32    public void setNumOfPages(int numOfPages) {
33        this.numOfPages = numOfPages;
34    }
35
36    public void printDetails() {
37        System.out.println("Title: " + title);
38        System.out.println("Author: " + author);
39        System.out.println("Number of Pages: " + numOfPages);
40    }
41}
42
43public class Main {
44    public static void main(String[] args) {
45        Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald", 180);
46        book.printDetails();
47    }
48}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment