Java Tutorial #17 — Encapsulating programs // including more than 1 file

Topics discussed: Encapsulation by separating methods into new files.
Source Code Available Here

Program encapsulation
The concept of program encapsulation is simple: break things down into their component parts so when something breaks, it’s easy to track, and easier to fix. The more ‘parts’ you break your program into (via methods) the easier this becomes. But as you increase the number of methods, the length of a single file becomes unmanageable and huge. Somewhere around 100-400 lines, a file becomes “hard” to read, so keeping it below that level is optimal (in my opinion) if at all possible.

Adding in additional files
In netbeans we will select a new file, and then simply add a new java class file to an existing project. The only thing that really changes in terms of code is that when we call a method from another file, we need to include the class name in the call to that method. Something like this:

//Normal header here

int x=0;
x= HandleX.addfive(x);


public class{

public static int addfive(int x){

return (x+5);

}//End method

}// End class

In the example above you’ll notice that the method is called by it’s filename first when we are in another file. This happens because we need to tell the compiler where to find the method that we’re trying to use.