Java- Data Hiding, Abstraction, Encapsulation

OOPS - Data Hiding, Abstraction, Encapsulation

1.Data Hiding

Hiding of data, so that out side person can’t access our data. The main advantage of data hiding is we can achieve security.

using ‘private’ modifier we can achieve data hiding.

class datademo
{
private double amount;
………
}


2.Abstraction

Hiding implementation details is nothing but abstraction. The main advantages of abstraction are we can achieve security as we are not highlighting internal implementation.

using interfaces & abstract classes we can achieve data Abstraction.


3.Encapsulation

Wrapping data and methods with in classes in combination with implementation hiding (through access control) is often called encapsulation.

If a class follows Data Hiding and Abstraction such type of class is said to be ‘Encapsulated’ class.

Encapsulation = Data Hiding + Abstraction


Abstraction VS Encapsulation

  • Abstraction is more about ‘What‘ a class can do. [Idea]

  • Encapsulation is more about ‘How‘ to achieve that functionality. [Implementation]

class Account {

private int balance;

public void setBalance(int balance) {

this.balance = balance; // validating the user & his permissions.

}

public int getBalance() {

return balance; // validating the user and his permissions.

}

}

Encapsulation essentially has both i.e. information hiding and implementation hiding.


Tightly Encapsulated Class

A class is said to be tightly encapsulated iff all the data members declared as private.

  • Only data memebers should private. getters, setters & other methods are not required to be private.

  • if the parent class is not tightly encapsulated then no child class is tightly encapsulated.

class x {
	int i = 0;
}
class y extends x {
	//int i -> hides as public
	private int j = 20;
}
class z extends y {
	//int i -> hides as public
	private int k = 30;
}