iForeRunner
 
   
 
  JAVA  
   
   
   
 
  Java| OOPS| encapsulation |example  
 
 



OOPs Concepts
Encapsulation

Encapsulation is the process of combining instance variables and methods into a type of structure usually called as "Class". In java language we can't write a single tiny program without using class. Imagine you have a code for a class and other programmers wrote code by making use of your class. But their code changes your instance variables values. Their code bought errors in your code. This type scenario might happen in structured programming languages. But this is a java program you are able to bring out newer version of the class, which other programmers could replace in their code without changing your code. This scenario brings the three key benefits which we stated earlier flexibility, maintainability and extensibility. But these benefits will not come automatically. You have to write your code that should support the benefits. If you made your instance variables as Public other programmers can change their state (here state means the values). So you have to keep your class instance variables private or protected. But here you may ask a question that how could we access these protected instance variables? Here we have to make our instance methods public and we can access protected variables through these public methods.

The ability to change the behavior of your code without changing your implementation code is a key benefit of encapsulation. You want to hide implementation details behind a public programming interface. By interface, we mean the set of accessible methods your code makes available for other code to call-in other words, your code's API. By hiding implementation details, you can rework your method code without forcing a change in the code that calls your changed method.

If you want maintainability, flexibility, and extensibility

1.Keep instance variables protected (with an access modifier, often private).

2. Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable.

3. For the methods, use the JavaBeans naming convention of set and get.

public class Box {

// protect the instance variable;
//Only an instance of Box Class can access it

private int size;

// Provide public getters and setters

public int getSize() { return size; }

public void setSize(int newSize) {
size = newSize;
}
} //This should be saved in Box.java


class BoxMain
{
public static void main(String args[])
{

//create instance of Box

Box b=new Box();

//access methods trough box objects

b.setSize(25);
System.out.println("Size:"+b.getsize());
}

//This program should be saved in BoxMain.java

Compile both the classes

c:/>javac Box.java

c:/>javac BoxMain.java

Run the BoxMain Class

c:/>java BoxMain

Output:
Size:25



Output of the program is as follows:
PRINT NAME: Venu Gopal Darur
PRINT NUMBER: 0
PRINT ONE 1