ENCAPSULATION
Encapsulation is one of the fundamental Object-
Oriented Programming oops in java
It used to wrapping the private
data(variables)and the public(methods)into a
single unit
(Point: private data’s can't be access one java
class to another java class)
To access private data into public methods need
to use predefined of setter and getter
Using a setter method we can access and modify
the private data(variables)
Using a getter method we can access and read
the private data(variables)
We can use get method without set method
We can use set method without get method
If we need to use setter and getter for private
methods a methods should be in return type
package javaprogram;
// encapsulation sample program............
class A
{
private int a=200; // private variable in
subclass
private String user() // private method in
subclass
{
System.out.println("private method
executing...");
return "return a string for private
method.....";
}
// set method used to write ,change or modify
private data
void setA(int a)
{
this.a=a; // using a this keyword link
instance variable to local variable
}
// get method used to read the the private data
int getA()
{
return a; // return a private data value
}
// if using a return type method we can access
private method one class to another class
String getUser()
{
return user();
}
}
public class javainheritance {
private int b=200;
private void mainclassmethod()
{
System.out.println("main class private
method.....");
}
public static void main(String[] args) {
// calling subclass private properties
A ob1=new A();
ob1.setA(300);
System.out.println(ob1.getA());
System.out.println(ob1.getUser());
// calling mainclass private properties
javainheritance ob=new javainheritance();
System.out.println(ob.b);
ob.mainclassmethod();
//
}
}