The following code shows an Example of Encapsulation in Java.
In this example we have a Book class that has certain data members and instance methods. Basically, the instance methods are getters and setters. So, here instance variables and methods are encapsulated in the class Book. In other words, the methods and data members are bind together so that the data members can be accessed using their corresponding getter and setter method.
Furthermore, the attribute author in the Book class encapsulates the information about the book author. Likewise, the Author class also encapsulates the attributes and methods of the Author object.
class Author {
String name;
String email;
char gender;
public Author(String name, String email, char gender) {
super();
this.name = name;
this.email = email;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
}
class Book {
String name;
Author author;
double price;
int qtyInStock;
public Book(String name, Author author, double price, int qtyInStock) {
super();
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQtyInStock() {
return qtyInStock;
}
public void setQtyInStock(int qtyInStock) {
this.qtyInStock = qtyInStock;
}
}
public class BookExercise1 {
public static void main(String[] args) {
Author auth=new Author("Kavita", "kavita@gmail.com", 'F' );
Book mybook=new Book("Python Programming", auth, 865.0, 7);
System.out.println("Book Details: ");
System.out.println("Book Title: "+mybook.getName());
System.out.println("Book Author: "+mybook.getAuthor().getName()+", "+mybook.getAuthor
().getEmail()+", "+mybook.getAuthor().getGender());
System.out.println("Price: "+mybook.getPrice());
System.out.println("Quantity in Stock: "+mybook.getQtyInStock());
}
}
Output