Methods and Constructors


You are already familiar with one particular method:
	public static void main(String args[])
Let's take a look at this method signature piece by piece:

The particular parts we will be using for writing our own methods, based on the information above, are:

An example:

Let's say we want to write a program that will take two numbers. The first number is the base, and the second is the exponent. The program will calculate the value of the base raised to the power of the exponent, ie: 5 to the 2nd power is 25.

		public class SomeClass {

			public static void main(String args[]) {

				if ( args.length == 2 ) {
					int base = Integer.parseInt(args[0]);
					int exponent = Integer.parseInt(args[1]);
					int result = 1;

					for ( int i=0; i<exponent; i++ ) {
						result *= base;
					}

					System.out.println("" + base
						+ " to the power of " + exponent
						+ " equals " + result"
					)
				} else {
					System.out.println("You must enter two numbers.");
				}

			}
		}

Notice that all of our logic is inside the "if" part. This is fine for a small program such as this. But, if the program gets larger, it becomes cumbersome to keep it all there.

The solution is to create separate methods for the logical processes. These methods would be private to the class. The logical process here to separate out would be the calculation.

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

				if ( args.length == 2 ) {
					int base = Integer.parseInt(args[0]);
					int exponent = Integer.parseInt(args[1]);

					int result = calculatePower(base, exponent);

					System.out.println("" + base
						+ " to the power of " + exponent
						+ " equals " + result"
					)
				} else {
					System.out.println("You must enter two numbers.");
				}

			}

			private int calculatePower(int base, int exponent) {
				int result = 1;

				for ( int i=0; i<exponent; i++ ) {
					result *= base;
				}

				return result; // required to return if not void
			}
		}
For a simple program such as this, the advantage is not immediately obvious. However, what we've created is a more modular and easier to follow program by separating out the logical processes.

NOTE: Even though I've used the variables "base," "exponent," and "result" in both methods, they are not the same variables. Each declaration is local to the method in which it is used. The "base" in the main method is a different variable from the "base" in the calculatePower method.

A constructor is a special type of method. It is used when you want to create a class that will act as a data type. The constructor is used to instantiate an instance of the class. Instantiating an instance means the same as declaring a variable of that class type.

A common example is the String class. Usually, you declare a variable of type string as follows:


	String someString = "";
Since String is technically as class itself (look in the java docs under the java.lang package), you could also declare it this way:
	String someString = new String();
The difference here is that you are using the keyword "new" and calling the constructor of the String class.

The constructor always has the same name as the class itself.

Let's create a class for calculating the power of a number.

	public class PowerCalculator {

		private int result = 0;

		public PowerCalculator() {
			//empty constructor that does nothing
		}

		public PowerCalculator(int base, int exponent) {
			/*
			 * constructor that takes two arguments
			 * used for when you want to initialize the
			 * class with some start-up values
			 */

			calculatePower(base, exponent);
		}

		public int getResult() {
			// getter method for returning the result
			return result;
		}

		public void calculatePower(int base, int exponent) {
			result = 1;

			for ( int i=0; i<exponent; i++ ) {
				result *= base;
			}
		}
	}
A few things to note:

The "result" variable is declared as a class-level variable.

You use what's called a "getter" method to get the value of the class-level variable

The "calculatePower" method is now public.

We can use this class in two ways, because it has two constructors.

	public class SomeClass {
		/* Use #1
			instantiate the class
			call the calculatePower method
			get the result
			display the result
		*/
		public static void main(String args[]) {

			if ( args.length == 2 ) {
				int base = Integer.parseInt(args[0]);
				int exponent = Integer.parseInt(args[1]);
				int result = 0;

				PowerCalculator pc1 = new PowerCalculator();
				pc1.calculatePower(base, exponent);
				result = pc1.getResult();

				System.out.println("" + base
					+ " to the power of " + exponent
					+ " equals " + result"
				)

			} else {
				System.out.println("You must enter two numbers.");
			}

		}
	}

	public class SomeClass {
		/* Use #2
			instantiate the class with the arguments
			get the result
			display the result
		*/
		public static void main(String args[]) {

			if ( args.length == 2 ) {
				int base = Integer.parseInt(args[0]);
				int exponent = Integer.parseInt(args[1]);
				int result = 0;

				PowerCalculator pc2 = new PowerCalculator(base, exponent);
				result = pc2.getResult();

				System.out.println("" + base
					+ " to the power of " + exponent
					+ " equals " + result"
				)
			} else {
				System.out.println("You must enter two numbers.");
			}

		}
	}
Important Note: In order for the main method of your application class to be able to find the PowerCalculator class, both source code and class files MUST be in the same directory (folder).