Amazon Interview Question
Software Engineer / DevelopersEncapsulation is a process of restricting access to a class's features , at the same time grouping the class related methods in the same class to avoid code duplication. For example, to represent sorting algorithms, we can have a class like
class SortingAlgorithms{
public void bubbleSort(List<Strings> strLst){
}
public void selectionSort(List<String> strLst){ }
public void quickSort(List<String> strLst){ }
}
Other way of doing the same functionality is encapsulating those algorithms in separate classes
interface SortingAlgorithms
{
void sort(Collection<? extends Object> clt);
}
class QuickSort implements SortingAlgorithms
{
@Override
public void sort(Collection<? extends Object> clt)
{
// TODO Auto-generated method stub
}
}
class BubbleSort implements SortingAlgorithms
{
@Override
public void sort(Collection<? extends Object> clt)
{
// TODO Auto-generated method stub
}
}
In this way, we can encapsulate those sorting algorithms as classes
Benefits of Encapsulation:
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
The variables of the EncapTest class can be access as below::
/* File name : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}
This would produce following result:
Name : James Age : 20
Encapsulation is the mechanism which ensures the safe and effective access of Classes or objects. For any outside objects which messages are sent from, the only things they need to take care is the interface of target object, while they dont care how does target object implement these interface. The target objects also hold some their own data and methods that is invisible for outside world, which improves the stability of the program.
- FeiXuhust February 02, 2011