Encapsulation in java

Encapsulation is one of the four fundamental OOP concepts. Remaining three are inheritance, polymorphism, and abstraction.In the previous post, we have studied the Abstract class and interface.

In this post, we will focus on encapsulation.

Encapsulation controls the access to a particular class from outside world i.e. outside classes. We can make a class full encapsulated by making its data-members private.

The possible way to access those data-members or methods will be to make them public getter and setter in the class.

These set and get methods will be used to access the data.In this way, we can make the class Read-Only and Write Only.

 class Book {
	private String bookName;
	
	public String getName(){
		return bookName;
	}
	
	public void SetName(String bookName){
		this.bookName=bookName;
	}
}

class Test{	
	public static void main(String[] args){
		Book book = new Book();
		book.SetName("java book");   // using the set method
		System.out.println("Book name is "+book.getName());  // using the get method to access the bookname
	}
}
Output: Book name is java book
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...