Chapter VII

 

Creating Class Methods

 

Chapter VII Topics

 

   7.1   Introduction

   7.2   User-Declared Class Methods

   7.3   User-Declared Parameter Methods

   7.4   Void Methods and Return Methods

   7.5   Making a Utility Library Class

   7.6   Summary

 

  


7.1  Introduction

 

 

Chapter IV introduced a few Object Oriented Programming (OOP) concepts.  In particular, emphasis was placed on encapsulation.  You learned that an object is capable of containing both data, often called attributes, and action modules that can process data, called methods.  The lion's share of the Chapter IV revolved around using methods of existing classes.  You also learned the distinction between calling class methods with the class identifier and object methods with the object identifier.  Class methods are normally a utility type of method that does not access changing data fields.  The Math class is a good example of a class where data will not change.  There are many methods in the Math class, but only two data fields, PI and E, which do not change.  Methods in Math are class methods and must be accessed using the Math class identifier.

 

It is a different story when you have the need to use methods with different sets of data.  A new and separate object needs to be constructed for each required variable.  A class is a data type and capable of only storing information for one single occasion.  This presents no problem for a utility class, which does not store any user provided data.  However, most classes require variables for many different data storage situations.  In the last chapter I showed you the Bank class.  That is a good example of a class, which requires multiple objects, one for each customer of the Bank class. 

 

In the statement int num;  int is the type and num is the variable.  Likewise in the statement Bank tom; the class Bank is the type and the object tom is the variable. 

 

There is a very important distinction between simple data types like int, double, char, and boolean and data types like Math, Random and DecimalFormat.  Each one of the simple data types stores only a single value.  Single value data types are more formally called primitive data types.  The variable objects of a class data type, on the other hand, can store many values.  Additionally, class data types also contain the methods, which access and process any stored data.

 

As you saw examples of class methods and object methods, you also learned that methods can have one or more parameters or arguments.  Parameters provide information to methods for processing.  Additionally, methods fall into two major categories, which are return methods and void methods.  Return methods return some requested value, like the tom.getChecking(); method, which returns the checking account balance of the object tom.  Void methods do not return any values, but frequently alter object data, like the tom.changeChecking(2000.0); method, which adds $2000.00 to the checking account balance of the tom object.   

 

You were told that learning OOP will not happen in one section, one chapter or even a couple of chapters.  It will happen throughout the entire course.  In the last chapter you were introduced to some general concepts of Object Oriented Programming and then you learned how to use existing class methods and existing object methods.  In this chapter you will learn how to write your own class methods and in the next chapter you will learn how to write your own object methods.  You have already learned that there is a distinction in using or calling class methods and object methods.  There is also a difference in writing class methods and object methods.

 

 

 

 

 

 

 

7.2  The Math Class Revisited

 

 

The Math class was used in the last chapter because students can easily identify with the methods of the Math class.  Program Java0701.java, in figure 7.1, calls the majority of the Math methods in one program.  This will review how to call class methods and it will also introduce various Math methods that were not shown in the last chapter.  It is possible that these math functions are unfamiliar to you.  You will learn about them in Algebra II and Pre-Calculus.  Later in the course we will use some of the trigonometric functions with graphics programs.

 

 

Additional Math Methods (not shown in the last chapter)

 

Math.exp(p)                  returns the antilog of the p

 

Math.log(p)                   returns the log (base e) of p

 

Math.sin(p)                   returns the trigonometric sine of p

 

Math.cos(p)                  returns the trigonometric cosine of p

 

Math.tan(p)                   returns the trigonometric tangent of p

 

Math.toDegrees(p)     returns the degrees of the radian value of p

 

Math.toRadians(p)      returns the radians of the degrees value of p

 

 

Figure 7.1

// Java0701.java

// This program reviews using class methods and demonstrates most of the

// available <Math> class methods and data fields.

 

 

public class Java0701

{

      public static void main (String args[])

      {

             System.out.println("\nJAVA0701.JAVA\n"); 

             System.out.println("The value of E is                               " + Math.E);

             System.out.println("The value of PI is                              " + Math.PI);

             System.out.println("The absolute value of (-25)  is               " + Math.abs(-25));

             System.out.println("The square root of (1024) is                  " + Math.sqrt(1024));

             System.out.println("The ceiling of (5.00001) is                " + Math.ceil(5.00001));

             System.out.println("The floor of (5.99999) is                  " + Math.floor(5.99999));

             System.out.println("The round of (5.50001) is                " + Math.round(5.50001));

             System.out.println("The antilog of (4.605170185) is       " + Math.exp(4.605170185));

             System.out.println("The log of (100) is                                  " + Math.log(100));

             System.out.println("The max of (1000,999) is                 " + Math.max(1000,999));

             System.out.println("The min of (1000,999) is                  " + Math.min(1000,999));

             System.out.println("The power of (4,3) is                       " + Math.pow(4,3));

             System.out.println("The random of () is                                 " + Math.random());

             System.out.println("The sine of (0) is                              " + Math.sin(0)); 

             System.out.println("The cosine of (3.141592653) is       " + Math.cos(3.141592653));

             System.out.println("The tangent of (0.785398163) is      " + Math.tan(0.785398163));

             System.out.println("The toDegrees of (3.141592653) is       " + Math.toDegrees(3.141592553));

             System.out.println("The toRadians of (180) is                 " + Math.toRadians(180));

             System.out.println();

      }

}

 

 

Java0701.java Output

 

JAVA0701.JAVA

 

The value of E is                 2.718281828459045

The value of PI is                3.141592653589793

The absolute value of (-25)  is   25

The square root of (1024) is      32.0

The ceiling of (5.00001) is       6.0

The floor of (5.99999) is         5.0

The round of (5.50001) is         6

The antilog of (4.605170185) is   99.9999999011909

The log of (100) is               4.605170185988092

The max of (1000,999) is          1000

The min of (1000,999) is          999

The power of (4,3) is             64.0

The random of () is               0.01121148441785591

The sine of (0) is                0.0

The cosine of (3.141592653) is    -1.0

The tangent of (0.785398163) is   0.9999999992051033

The toDegrees of (3.141592653) is 179.9999942366294

The toRadians of (180) is         3.141592653589793

 

 

 

 

 

7.2  User-Declared Class Methods

 

 

It is nice to use other people’s tools.  It can save time and make program writing much less tedious.  You are ever so pleased that Java has cordially provided you with the Math class, Random class and DecimalFormat class, complete with a set of methods to make your programming life simpler.  At the same time you should now  start to try out your own wings.  What if you want to create your very own class, and create your very own methods?  Is that possible?  Is that difficult?  It is possible and difficult is a matter of perspective.  The classes shown in the next couple of program examples are not very impressive.  You may wonder why I would bother create classes for the simplistic output that they create.  That is fine.  The mission is to learn OOP step-by-step and this introduction is more comfortable on the neurons than the avalanche approach.

 

Program Java0702.java, in figure 7.2, displays a rather unimpressive mailing address.  The three println statements could have been all placed in the main method, as they were in previous programs.  This time there are three additional program modules.  The familiar main module is ever present and now there is also a module for fullName, street and cityStateZip.  The three new modules appear very similar in syntax to the main module.  They all start with public static void followed by a method identifier, like main.

 

Each module has opening and closing braces that contain a println statement.  In the main method there are three statements with the dot.method notation.  This class is not the earlier Math class or any other Java library class, but your very own class, Java0702.

 

Please keep in mind that next couple of program examples are designed to show the correct syntax for declaring a class with class methods.  They are not good examples of object oriented programming.  Better OOP programs and more practical classes will be shown later in the chapter and later in the course.

 

Often students are curious why a certain new concept is introduced.  There appears little justification for the new program feature.  It is easy enough for an author to show a truly practical program that is now much simpler because of the new and improved program concept.  Unfortunately, such practical programs tend to be very long and complex.  The new idea, being introduced, is totally hidden in complexity of hundreds of program statements.

 

 

 

 

 

Figure 7.2

// Java0702.java

// This program introduces user-created class methods.

// The three class methods are called with the same dot.method syntax

// as the methods of the Math class.

 

 

public class Java0702

{

     

      public static void main(String[] args)

      {

             System.out.println("\nJAVA0702.JAVA\n");

             Java0702.fullName();

             Java0702.street();

             Java0702.cityStateZip();

             System.out.println();

      }    

  

      public static void fullName()

      {

             System.out.println("Kathy Smith");

      }

 

      public static void street()

      {

             System.out.println("7003 Orleans Court");

      }

 

      public static void cityStateZip()

      {

             System.out.println("Kensington, Md. 20795");

      }

 

}

 

 

Java0702.java Output

 

JAVA0702.JAVA

 

Kathy Smith

7003 Orleans Court

Kensington, Md. 20795

 

 

 

 

All your previous program examples always had a class.  Java requires that programming is done with classes and an application program requires a main method.  Now we have been shoving all the program statements in the main method and that can get crowded and very unreadable.  It is much nicer to break up a program into manageable modules.  Each module uses the same format as you have been using for the main method.

 

 

 

 

Now how about a little surprise?  Program 0703.java, in figure 7.3, is almost identical to the previous program, but now the class identifier is totally ignored and the method identifiers are called without concern about any class identifier, object identifier or anything else.  How can that be correct?  Will that compile and execute?

 

 

Figure 7.3

// Java0703.java

// This program example displays the same output as the previous program.

// This time the methods are called directly without using the class identifier.

// Omitting the class identifier is possible because all the methods are

// encapsulated in the same class, Java0703.

 

 

public class Java0703

{

     

      public static void main(String[] args)

      {

             System.out.println("\nJAVA0703.JAVA\n");

             fullName();

             street();

             cityStateZip();

             System.out.println();

      }    

  

      public static void fullName()

      {

             System.out.println("Kathy Smith");

      }

 

      public static void street()

      {

             System.out.println("7003 Orleans Court");

      }

 

      public static void cityStateZip()

      {

             System.out.println("Kensington, Md. 20795");

      }

 

}

 

 

Java0703.java Output

 

JAVA0703.JAVA

 

Kathy Smith

7003 Orleans Court

Kensington, Md. 20795

 

 

 

There is Kathy Smith again and her address seems to indicate that the program compiled without any difficulties.  So why bother with class identifiers when they appear to be extra baggage?  It turns out that it is extra baggage in this particular example.  The three methods that are declared are all members of the Java0702 class.  It is not necessary to state the name when you are already in the same class. Consider this analogy.  A letter needs to be given to Tom Jones, who is in room J116 of Berkner High School during third period.  If this letter is delivered in the school’s office, some office aid is told to bring the letter to Tom Jones in room J116.  That makes sense.  Now suppose that I have a letter on my desk for Tom Jones and I am in room J116.  I hand the letter to a student next to my desk and tell the student to give it to Tom Jones.  I do not bother to add that Tom Jones is in room J116.  I am in room J116, the student delivering the letter is in room J116 and Tom Jones is in room J116.  It does not seem necessary to add that piece of information to make the delivery possible.

 

 

Figure 7.4

Using the Class Identifier

 

Use of the class identifier is optional if a method is called from

a program statement in another method, which resides in the same class as the method being called.

 

Use of the class identifier is required if a method is called in

a program statement that resides outside the class of the

method that is being called.

 

 

 

Proof about the class identifier statement made in figure 7.4 is provided with program Java0704.java.  That program declares a second class, called Address.  The methods of fullName, street and cityStateZip are declared as members of the Address class.  These same methods are called, as before, from the main method of the Java0704 class.  This time fullName, street and cityStateZip are no longer members of the Java0704 class and the program will not compile.

 

You have not seen a second class declaration in any previous program.  Declaring a second class is not a problem.  The syntax of a second class is almost identical to the primary class with one important distinction.  A second and third class should not be declared as public.  Only the primary class with the same name as the file is public.  Java0704.java, in figure 7.5, does not compile because it does not know what to do with the method calls.  Look at the many error messages to realize how confused the compiler is.

 

 

 

 

 

Figure 7.5

// Java0704.java

// This program demonstrates how to use a second class separate from the

// main program class.  This program will not compile because the Name,

// Street and CityStateZip methods are no longer encapsulated in Java0704.

 

 

public class Java0704

{ 

      public static void main(String args[])

      {

             System.out.println("\nJAVA0704.JAVA\n");

             fullName();

             street();

             cityStateZip();

             System.out.println();

      }

}

 

 

class Address

{

      public static void fullName()

      {

             System.out.println("Kathy Smith");

      }

 

      public static void street()

      {

             System.out.println("7003 Orleans Court");

      }

 

      public static void cityStateZip()

      {

             System.out.println("Kensington, Md. 20795");

      }

}

 

 

 

Java0704.java Output

 

C:\Java\Progs07>javac Java0704.java

Java0704.java:12: cannot resolve symbol

symbol  : method fullName  ()

location: class Java0704

                fullName();

                ^

Java0704.java:13: cannot resolve symbol

symbol  : method street  ()

location: class Java0704

                street();

                ^

Java0704.java:14: cannot resolve symbol

symbol  : method cityStateZip  ()

location: class Java0704

                cityStateZip();

                ^

3 errors

 

 

 

Program Java0707.java, in figure 7.6, solves the problem of the previous program by using the Address class identifier.  More importantly, it demonstrates that you can really have multiple classes in one program.  As your program grows in complexity, you will learn that it is customary to have only one class for one program file.  Right now it is simple to demonstrate new concepts when all the concepts are in the same program file.

 

 

Figure 7.6

// Java0705.java

// The problem of Java0704.java is now fixed.  It is possible to declare

// multiple classes in one program.  However, you must use the dot.method

// syntax to call any of the <Address> class methods.

 

 

public class Java0705

{ 

      public static void main(String args[])

      {

             System.out.println("\nJAVA0705.JAVA\n");

             Address.fullName();

             Address.street();

             Address.cityStateZip();

             System.out.println();

      }

}

 

 

class Address

{

      public static void fullName()

      {

             System.out.println("Kathy Smith");

      }

 

      public static void street()

      {

             System.out.println("7003 Orleans Court");

      }

 

      public static void cityStateZip()

      {

             System.out.println("Kensington, Md. 20795");

      }

}

 

 

 

Java0705.java Output

 

JAVA0705.JAVA

 

Kathy Smith

7003 Orleans Court

Kensington, Md. 20795

 

 

 

 

7.3    User-Declared Parameter Methods

 

 

This chapter started by showing many of the methods available in the Math class.  The majority of those methods used arguments or parameters to perform the desired computation.  Math.random() is one of the few methods, which  does not use a parameter.  As you looked at the program examples with user declared methods, you noticed that all these methods were void of parameters.

 

 

Methods Calls with and Without Parameters

 

Parameter method example where 100 is the parameter or argument of the sqrt method.

 

Result = Math.sqrt(100);

 

 

No-Parameter method example:

 

RndNumber = Math.random();

 

 

 

You will find that most methods require parameters.  This is very natural because methods perform some type of task.  In most cases the task requires the processing of some type of data.  There certainly are situations where the data to be processed already belongs to the class.  In such situations, parameters are not necessary.  There are also plenty of processes where external information needs to be processed and such information arrives to the method by parameter.

 

Program Java0706.java, in figure 7.7, has a Demo class with four methods.  You will note that the method declarations are identical to any other user-created methods you have seen previously with one addition.  Inside the parentheses is a variable declaration.  The variable declared in the method heading receives a copy of the values that is passed by the parameter of the method call.  Look at the program example first and then we need to talk some more to make sure that you understand the difference between the parameters in the method call and the parameters in the method heading.

 

 

 

 

Figure 7.7

// Java0706.java

// This program demonstrates how to write methods with parameters.

 

public class Java0706

{

 

      public static void main(String args[])

      {

             System.out.println("\nJAVA0706.JAVA\n");

            Demo.method1();                                                       // no parameter method call

             Demo.method2(1000);                                               // one int parameter method call

             Demo.method3(1000,2000);                                            // two int parameters method call

             Demo.method4("Hans",30,3.575);                             // three different type parameters method call

             System.out.println();

      }    

  

}

 

 

class Demo

{

     

      public static void method1()

      {

             System.out.println("\nMethod1 has no parameters");

      }

  

      public static void method2(int intNum)

      {

             System.out.println("\nMethod2 has one parameter, " + intNum);

      }

  

      public static void method3(int intNum1, int intNum2)

      {

             System.out.println("\nMethod3 has two parameters, " + intNum1 + " and " + intNum2);

      }

     

      public static void method4(String studentName, int studentAge, double studentGPA)

      {    

             System.out.println("\nMethod4 has 3 parameters with three different types");