Encapsulation
Encapsulation
Encapsulation is mechanism that bind data and methods it manipulates into one unit. This is
used to hide internal representation from outside the class and misuse.
Encapsulation can be achieved by using access modifier i.e. private or protected. The data
member to be hidden should be labelled as private or protected.
The following program illustrate the same
class test
{
int a;
public int b;
private int c;
void assignc(int i)
{
C = i;
}
int getc()
{
return(c);
}
}
class mainclass
{
public static void main(String args[])
{
test obj = new test();
obj.a = 10;
obj.b = 20;
// obj.c = 30; This is not allowed. The same can be through assignc method
obj.assignc(30);
System.out.println(“ a = “ + obj.a);
System.out.println(“ b = “ + obj.b);
// System.out.println(“ c= “ + obj.c);
// the above statement is not allowed. Value of c is printed as follows
System.out.println( “c = “ + obj.getc());
}
}
Packages
Packeges are way of grouping a variety of classes and/or interfaces together. The grouping
is usually done according to functionality. The classes in the packages of other programs can be
easily reused. Packages provide a way to hide classes.
Java packages are classified into two type i.e. Java API and user defined packages.
API packages
Java API has number of classes grouped into different packages according to the
functionality. The frequently use API packages are lang, util, io, awt, net, applet etc
java.lang - Java compiler use these classes and they are automatically imported. They include
classes for primitive data type, strings, math function, threads and exception.
java.util - it contains utility classes like vector, hash tables, random number, date etc
java.io - it provides facilities for the input and output of data.
java.awt - It include classes for windows, button, lists, menus
java.net - Includes classes for communicating with local computer with internet server.
java.applet - Includes classes for creating and implementing applets.
}
public void calcpercentage()
{
}
public void addstudent()
{
}
}
The above code violets single responsibility principle. By using the single responsibility
principle, it is possible to separate functionalities into three different class. To achieve SRP, the
program becomes
public class printstudentdetails
{
public void printdetails()
{
}
}
}
}
}
}