Posted about 1 year ago, by Specific

After reading this tutorial, you should be able to: Define an instantiable class with multiple methods and constructors, differentiate the local and instance variables, use value-returning methods, distinguish private/public methods and members, know how arguments are passed to the parameters in method definitions, how the result is returned from a method, and define a reusable class for handling input routines.

If you have not read my article "Your First Java Program" (opens in new window), I suggest that you read before continuing with this tutorial.

The program we made in the article above only included one class, the main class of the program.  And the main class contained only one method, the main method.  From this main method, we used only objects from javax.swing standard package.  For very small programs, this arrangement may be acceptable, however, for large programs it is not.  Placing all code for a large application in a single method main makes the method huge and impossible to manage.  For very large applications, these predefined classes alone cannot satisfy all of our programming needs.

Learning how to define your own classes is the first step towards mastering the skills necessary in builiding large programs.  In this tutorial we will learn how to define instantiable classes and different types of methods included in the instantiable classes.  A class is instantiable if we can create instances of the class.  The String class is instantiable while the Math class is not.

When you are designing a program, it is a good idea to write out what you would like the program to do.  An example would be a traffic light.  How would we make a program to control a traffic light?  We know that a traffic light has three colors: red, yellow, and green.  If we were to think of these as seperate states, they would be: stop, yield, and go!  We will need a some way to switch between these states as they do with a traffic light.  Traffic light will start with red (stop), green (go), yellow (yield), and start the cycle over. 

We will start with creating our traffic light class:

In classes, you define members and methods as Private or Public. The difference between them is just that.  Private methods or members will only be seen by the class itself.  Public methods can be seen by everything.

To use this in your main class of your program you would first define the class and call cycleLight() method.  Your program will then run the light.

Author Info Comment