Difference Between Information Hiding and Encapsulation (#14886)

* Difference Between Information Hiding and Encapsulation

* Difference Between Information Hiding and Encapsulation
This commit is contained in:
Michael Olayemi 2023-10-13 12:06:18 +00:00 committed by GitHub
parent ee98df03f4
commit 604c45b8f0
5 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,7 @@
package com.baeldung.encapsulation;
public class Book {
public String author;
public int isbn;
}

View File

@ -0,0 +1,8 @@
package com.baeldung.encapsulation;
public class BookDetails {
public String bookDetails(Book book) {
return "author name: " + book.author + " ISBN: " + book.isbn;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.encapsulation;
public class BookEncapsulation {
public String author;
public int isbn;
public int id = 1;
public BookEncapsulation(String author, int isbn) {
this.author = author;
this.isbn = isbn;
}
public String getBookDetails() {
return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.encapsulation;
public class BookInformationHiding {
private String author;
private int isbn;
private int id = 1;
public BookInformationHiding(String author, int isbn) {
setAuthor(author);
setIsbn(isbn);
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
if (isbn < 0) {
throw new IllegalArgumentException("ISBN can't be negative");
}
this.isbn = isbn;
}
public String getBookDetails() {
return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.encapsulation;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class EncapsulationAndInformationHidingUnitTest {
@Test
public void givenUnencapsulatedClass_whenImplementationClassIsSeparate_thenReturnResult() {
Book myBook = new Book();
myBook.author = "J.K Rowlings";
myBook.isbn = 67890;
BookDetails details = new BookDetails();
String result = details.bookDetails(myBook);
assertEquals("author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
}
@Test
public void givenEncapsulatedClass_whenDataIsNotHidden_thenReturnResult() {
BookEncapsulation myBook = new BookEncapsulation("J.K Rowlings", 67890);
String result = myBook.getBookDetails();
assertEquals("author id: " + 1 + " author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
}
@Test
public void givenEncapsulatedClass_whenDataIsHidden_thenReturnResult() {
BookInformationHiding myBook = new BookInformationHiding("J.K Rowlings", 67890);
String result = myBook.getBookDetails();
assertEquals("author id: " + 1 + " author name: " + myBook.getAuthor() + " ISBN: " + myBook.getIsbn(), result);
}
}