Java, like most object oriented languages, separates codes into smaller chunks for easier maintainability and re-usability. You as a programmer have an option of separating code out to different methods within the class you're currently working on, or if enough related methods accumulate, to it's own separate class.
In Java, if you place the classes within the same directory you may call each class's methods, as long as they're public. To give you an example, we'll create a RandomCharacter class that generates and returns random characters, and a separate TestRandomCharacter class that utilizes the code from the RandomCharacter class.
Looking at the class below (RandomCharacter), you'll notice that there are 5 methods within the class. Each method does something different: refer to the notation above each method for the overview.
Now that we have the class setup, we can call the methods from this class within our TestRandomCharacter class. Note that the RandomCharacter class does not have a main() method. The class is simply a collection of methods and will not run by itself if you were to execute it.
In the TestRandomCharacter class, we iterate through the for loop 176 times. Through each iteration, we call the getRandomLowerCaseLetter() method located in the RandomCharacter class and store the result within the ch variable. We then display the characters, either on the same line or the next, depending on if we reached our 25 characters per line cap.
That's it. Pretty simple stuff.
In Java, if you place the classes within the same directory you may call each class's methods, as long as they're public. To give you an example, we'll create a RandomCharacter class that generates and returns random characters, and a separate TestRandomCharacter class that utilizes the code from the RandomCharacter class.
Looking at the class below (RandomCharacter), you'll notice that there are 5 methods within the class. Each method does something different: refer to the notation above each method for the overview.
Now that we have the class setup, we can call the methods from this class within our TestRandomCharacter class. Note that the RandomCharacter class does not have a main() method. The class is simply a collection of methods and will not run by itself if you were to execute it.
In the TestRandomCharacter class, we iterate through the for loop 176 times. Through each iteration, we call the getRandomLowerCaseLetter() method located in the RandomCharacter class and store the result within the ch variable. We then display the characters, either on the same line or the next, depending on if we reached our 25 characters per line cap.
That's it. Pretty simple stuff.
Comments
Post a Comment