encapsulation in java programs
// java program on encapsulation
class EncapsulationExample
{
private int ID;
private String stuName;
private int stuAge;
// getter and setter methods
public int getStudentID()
{
return ID;
}
public String getStudentName()
{
return stuName;
}
public int getStudentAge()
{
return stuAge;
}
public void setStudentAge(int number)
{
stuAge = number;
}
public void setStudentName(String number)
{
stuName = number;
}
public void setStudentID(int number)
{
ID = number;
}
}
public class ExampleForEncapsulation
{
public static void main(String[] args)
{
EncapsulationExample student = new EncapsulationExample();
student.setStudentName("Virat");
student.setStudentAge(5);
student.setStudentID(2353);
System.out.println("Student Name: " + student.getStudentName());
System.out.println("Student ID: " + student.getStudentID());
System.out.println("Student Age: " + student.getStudentAge());
}
}
// Java program to demonstrate encapsulation
public class Encapsulate
{
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;
// get method for age to access
// private variable geekAge
public int getAge() {
return geekAge;
}
// get method for name to access
// private variable geekName
public String getName() {
return geekName;
}
// get method for roll to access
// private variable geekRoll
public int getRoll() {
return geekRoll;
}
// set method for age to access
// private variable geekage
public void setAge( int newAge) {
geekAge = newAge;
}
// set method for name to access
// private variable geekName
public void setName(String newName) {
geekName = newName;
}
// set method for roll to access
// private variable geekRoll
public void setRoll( int newRoll) {
geekRoll = newRoll;
}
}
public class TestEncapsulation {
public static void main (String[] args) {
Encapsulate obj = new Encapsulate();
// setting values of the variables
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
// Displaying values of the variables
System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());
System.out.println("Geek's roll: " + obj.getRoll());
// Direct access of geekRoll is not possible
// due to encapsulation
// System.out.println("Geek's roll: " + obj.geekName);
}
}