Skip Nav

Writing Classes and Javadoc

2. Create intriguing, complex characters

❶Now is an appropriate time to begin discussing the other end of exception processing: There are no local variables here, so we leave blank that part of the call frame.

1. Invoke multiple senses

1) The Snowflake Method
The Structure Behind Your Paper
2) The 30-Day Method

It should show your reader that your reserach has been carried out appropriately and, therefore, that the results can be believed. The elements included in the method section and the order in which they are presented may differ from department to department.

Read the following example of a method section from the field of computer assisted language learning and teaching. The study investigated the use of the World-Wide-Web for teaching writing in a British university. Identify the information elements you find in each sentence of the selection. Some sentences may contain more than one element. In early telephone interviews were conducted with a statewide probability sample of 2, registered voters in a major southwestern state.

The interviews were conducted for a state agency and addressed various voting-related attitudes and opinions. Within this context, a split ballot experimental design was employed whereby approximately each quarter of the sample was asked age utilizing a different question format. Three open-end and one closed-end question formats were investigated:. Each question format was drawn from previous research and was selected to be illustrative of one approach to asking age.

The particular question format used when asking an individual study participant his or her age was randomly determined prior to the interview. Interviewers made no determination as to what age question format was employed for a specific study participant. All interviews were conducted from a centralized, supervised interviewing location and began with an interviewer asking to speak to a prespecified individual.

The questionnaire consisted of 20 questions, of which the age question was number Actual age data were available from the state agency for 1, of the individuals interviewed.

But, most Java style standards DO NOT require specifying parameters as final , even if they remain unchanged in the body of a method. I'm still deciding what I think is right in this case; meanwhile, you can choose either to include final in the code you write, to emphasize that the parameter does not change, or omit it; whatever you choose, be consistent.

When designing a method, first think of a descriptive name for it; then think about the other prototype information: Parameter variables are used to convey special information to the method; information that controls what a method computes.

Methods may also have declare local variables, which are needed temporarily during the execution of a method; but these values do not have to be initialized by arguments outside the method. Finally, and this is typically the easiest part, write the statements that implement the method. Notice above that except for the promptInt methods, no others perform input or output. In some sense, methods get their "inputs" through their parameters; they supply their "output" either through a returned result or by changing the state of the objects that their parameters refer to.

Everything in Java is defined in a class: The EBNF for a class relies heavily on the definition of full-member-definition note package and class are keywords. Most classes in Java are defined in their own. Let's examine the three major parts of a class definintion.

Every class is defined in one package, specified in the package-statement ; if this option is omitted, the class is said to be defined in the anonymous package the name of the anonymous packages has no characters in it. Whatever package this class is in, all other classes in that package are automatically imported for use in it.

Second, if this class must refer to any classes in other packages, they must be imported explicitly in an import-declarations. Finally, the class itself is defined: Here is a trivial but complete class named Application. After discussing main methods, will see how to define complete classes for simple Java programs and libraries that define other methods. Any Java class can define a special main method as one of its members; but, a method with this name is special only if it has exactly the following access modifiers and header This method specifies an array of String as its parameter, although we will not use this parameter until we study how to use Java from a command line; we will see below how to tell the Eclipse IDE which special main method to execute.

In fact, any project can include multiple classes, and each class can have its own special main method this is actually quite useful, and we will discuss this feature when we discuss testing classes in more detail. In Eclipse, we specify the class whose main method is to be run by selecting the class either in the Package Explorer or in the Editor. We have seen how to declare one special static method in a class and have Java execute that method.

Now we will learn how to define and call other static methods in a class. All we must do is place these other method definitions inside the class, along with the main method. Then, we can call these method from main or from each other. Any static method in a class can call any other static method in that same class, just by using its name and supplying arguments that match its signature or, if overloaded, one of its signatures.

We can also be a bit more consistent and verbose and call a static method by prepending the class name to the method's name. The following Application class shows a simple example of such code.

We have always called static methods in the form ClassName. Most programmers use this shortened form for method names. Another way to think about this issue is to imagine that a class is like a family: Each defined member's name is like a first name.

Members of the same family class can refer to each other by their first names only, without ambiguity. This is why main can refer just to factorial ; we do not need to write Application. But, when refering to some static member OUTSIDE your family class you must use both its last and first name separated, of course, by a period. This is why we write Math.

A more complicated and interesting example of static methods appears in the Date Calculator 1 program. This program defines and used five static methods and twelve static fields. Java uses a multi-pass compiler, which means that the methods and fields in a program can be defined in any order: Java first reads all the method headers and fields in the file, then in reads all the bodies, checking that they all use the types of these methods and fields correctly.

One standard way to write methods is in the "natural" order: The main method calls lots of other methods, so it typically appears last in the file. In the "reverse natural" order: In this case, the main method calls lots of other methods, so it typically appears first in the file. Because Java uses a multi-pass compiler, these two orderings, or any others, are all legal. When we discuss mutually recursive methods, we will return to this topic again. Now, some words on divide and conquer, and program complexity.

Up until now, we have been putting all of our code in the main method, some of which have been a hundred or more lines of code. This practice is stopping here! From now on, we will be distributing complexity by writing methods, and placing them in the application program, or in class libraries.

We can write, test, and debug each method and each class by idependently. Each method, including main , should not comprise more than one or two dozen statements; when a method gets too complicated it does "this" and "that" then write a "this" method and a "that" method, and have the original method call these two new methods to get its job done.

Another rule for keeping the complexity of each method small it to prohibit more than one loop the most complex Java statement to think about per method -or allow multiple loops, but not nested loops. Notice how the complexity has been distibuted in the date calculator program, in which each method, even main contains only a small number of statements.

We have already discussed how to handle thrown exceptions with try-catch statements. Now is an appropriate time to begin discussing the other end of exception processing: The EBNF rule for throwing an exception using the keyword throw is trivial: We will discuss class hierarchies later; for now we have seen the names of a variety of classes descended from Throwable: Exceptions are represented by classes; so, throwing an exception requires us to construct a new instance of the class, typically initializing its state by a String that describes the problem; this String can be further examined and printed when the exception is caught.

Given that our factorial method only works for non-negative integers, we might modify it as follows, to detect a bad argument and throw IllegalArgumentException with an appropriate message rather than just returning 1. Notice how throws IllegalArgumentException now appears in factorial 's signature. It is common to check all the necessary preconditions on arguments at the start of a method's body, grouping such code together and separating it from the code that actually performs the method's task which executes only after all the preconditions on the parameters have been checked.

In this example, if the argument matching parameter n is a negative value, Java constructs an instance of the IllegalArgumentException class initialized with an appropriate error message , and throws that exception.

When a statement throws an exception, Java abandons sequential execution and tries to locate a catch clause to handle the exception, first inside the method in which it was thrown; if the method itself doesn't have one, Java goes back to the call site for the method which is the body of some other method and repeats this process there. If by repeating this process, Java eventually gets back to the special main method, and if there is no matching catch clause to handle the exception, Java prints the exception name, the exception's message the String argument to the exceptions constructor , and a trace of all the methods that were called, leading up to the problem.

We will use throw statements as we continue to learn about writing constructors and methods in classes. We will come back to the topic of throw statements and try-catch statements, and exception classes at least once more in the context of class hierarchies , to help us further understand this complex error detection and recovery mechanism.

There we will learn how to write new exception classes and the difference between checked and unchecked exceptions. Although some static methods might be useful in just one application, many are general enough to be used in other similar applications. In Java, we can easily collect these methods into a class of related methods all the source code in the same file , which we can easily import and use in other programs.

The Math class in the standard Java library serves exactly this purpose, as doe the Prompt class in the course library: For example, we ccould easily group together all of the static methods and fields from the date calculator program into a DateUtility class as is shown below. Then, we could use such a class library in any program that must deal with dates. Examine the Date Calculator 2 program to see exactly how this mechanism works in a project.

Recall that final variables constants in Java are written as upper-case identifiers. If their name consists of multiple words, separate them by underscores: Given the use of a library class, the main method in the Application class must refer to its members by using both their class name and member name: Outside the class in the Application class we must refer to each static member by its class name followed by its member name.

Finally, note that there are no constructors for this class and likewise no instance variables. We do not construct objects from this class; we just use the class name directly to refer to the methods that we want to call from this class. Methods are so common in programming, various parts of the Eclipse IDE have been built to deal with them easily.

Here we will examine mechanisms in the Java and Debugger views that help us use methods in our programs. The editor includes a mechanism to locate and display a method easily in a program or library class. When a class is active in the editor, the Outline window lists all the methods in the class. We can easily view a method in the editor by clicking its name in the Outline window. As the number of methods in a class grows, this mechanism becomes more and more useful for quickly navigating files.

To the left of each method header is small shaded circle, containing either a minus sign or a plus sign. Clicking the circle toggles between disclosed and elided method bodies.

We can also use the debugger to better understand methods and debug methods that we have written. The options displayed when we are stepping through a program appear as Middle: The Step Over button the arrow pointing over a bar, as we have discussed executes a method as if it were a black box: The Step Into button the arrow pointing down between two bars executes a method by first showing its parameters and local variables in the Variables tab.

Then, we can step through each statement in the method and watch how it executes. If we step through a return statement, we will be returned to the code that called the method. If the method we are stepping through calls another method, we can choose to step-into or step-over that other call. The Step Out button the arrow pointing up out of two bars executes all the remaining statements in the current method, up to and including its return statement.

Note, the single bar for the middle button represents an entire statement. Stepping over it means ignoring the details of any methods that are called in that statement. The double bars in the left and right buttons represent a block of code implementing a method.

We can step into a method start executing the first line of code in the methods and step out of a method finish executing the last line of code in the method. When we step into a method, its parameter and local variables appear in the Variables tab. All its parameters will be intialized to the values of their matching arguments. The name of the method will also appear underneath Thread[main] at in the Debug tab.

If it calls another method, that method's name will appear above it now directly underneath Thread[main] ; whenever a method returns, its name is removed from the Debug tab and control returns to the method that called it the one right below it in the Debug tab. If you click any method name in the Debug tab, it will show you the code that is executing in that method in the editor window and that method's parameters and local variables in the Variables tab.

In this way, it is easy to shift focus among the methods that are currently executing. In the example below, we are looking at the bottom of the daysIn method; note its parameters have been initialized: In fact, this method has already called the isLeapYear method it is at the top of the methods, so it is the one currently executing , but we have refocused our attention back to the daysIn method that called it, by selecting this method in the Debug tab.

After we select the isLeapYear method and continue single-stepping, we return to the ordinalDate method, which shows the position it is executing in the body of the loop and all its parameters and local variables listed in the order they were declared in: Practice using these three kinds of stepping using the two Date Calculator programs.

The time you spend becoming familiar with debugging features will pay for itself many times over during the semester: We will now shift our focus from simple classes that have only static members towards more interesting and useful classes: Although instance variables are declared to be private , we wll learn that all other members in their class can manipulate them.

Then we will learn how to write constructors that help initialize these instance variables. Finally, we will build on our knowledge of methods to learn how to write methods that manipulate instance variables. We will discuss multiple uses of the keyword this in the context of classes from which we construct objects Classes in Java combine elements of both state and behavior. State is embodied in an object's private instance variables; behavior is embodied in the class's public constructors and methods, which manipulate these instance variables.

Programmers think about classes from three important and different viewpoints: Reading Javadoc is the prime way to learn this information. Typically, knowing WHAT requires reading Javadoc; knowing HOW requires writing Java code that specifies what state each object will store and how its method bodies work to manipulate this state.

This programmer is often presented with many interesting decisions, because there are many ways implement the same functionality. This person must decide what members to include and then specify the semantics of each member so that a users understand WHAT to do with the class and b implementors understand HOW to implement it. Designers do this by writing the public prototypes in a class and documenting them with Javadoc. These three views are a bit of a simplification, because often one person takes multiple roles, even all three: Good design is hard.

In this course we will mostly take the roles of users as we have in previous lectures and implementors as we will in this one. As implementors, we will typically be given a design, and then be required to implement it. To accomplish this process, we will have to indentify the state that each object stores, then declare it and define the required constructors and methods. Finally, who tests classes? We will see that classes may be tested from all three prespectives. The designer tests a class by developing a test suite along with the Javadoc; because the designer doesn't know anything about the implementation, this is black-box testing.

Some test suites are open-ended a driver and some are closed we will learn about JUnit testing. The implementor tests a class by running the designer's tests against the implementation, fixing errors exposed by the testing. The implementor might also develop further tests based on the actual implementation used this is white-box testing. The user of a class implicitly tests it in an application program: The situation of a non-working application is interesting.

Whose fault is it: To illustrate all this material, we will closely examine two classes and their drivers: Let's start by looking at the implementation details for two sample classes. The SimpleDiceEnsemble class must store information characterizing the ensemble number of dice and sides per die and information about its current state number of rolls, pip sum, whether all die show the same numer of pips.

It declares its instance variables as follows. Another perspective is that instance variables are private details, so declaring them at the bottom out of the way is reasonable. Whenever new constructs an object, the first thing that it does is process all the field declarations in the class, which includes reserving space for all these field and initializing them.

So technically, when a constructor stores a value into an instance variable, it is reinitialization, not initialization, because an initial value has already been stored there by Java, when it executes its declaration. Still, we will speak about initializing instance variables in constructors and reinitialization if we want to be precise.

The main purpose of any constructor is to ensure that all the instance variables of the object being constructed are initialized correctly. This is done in the body of the constructor, which contains exactly the same statements that can appear inthe body of a void method. For some instance variables a constructor may do nothing special: In other cases it initializes actually reinitializes, given the discussion above instance variables using the arguments passed to the constructor's parameters; the constructor often validates these arguments first throwing IllegalArgumentException if they are incorrect.

There are classes, some quite complicated, in which constructors take no arguments and reinitialize no fields. In these cases, the fields are initialized correctly in their declarations either explicitly or implicitly. The Timer class is one example of this kind of class. But, if we define even one constructor for a class, Java will not overload the constructor s by defining this one.

Most classes define at least one constructor and many overload the constructor. These constructors always have parameter that help reinitialize instance variables. If the parameters do make sense, it copies them into two of the instance variables reinitializing them. The other three instance variables are not reinitialized: Variable Name Conflicts and Resolving them with "this".

We must take a briefly diversion to discuss variable name conflicts and how to resolve them with the keyword this. There are three kinds of variable names in Java. But, Java does allow instance variables to have the same names as parameters or local variables.

When this happens, it is called a variable name conflict, because when we use that common name, there is a conflict as to what it means. If instead we want to refer to the instance variable, we must preface its name with this. In a constructor, this is a reference to the object being constructed; and this. In fact, writing this. So, in the constructor above, both parameter variables have a name conflict with two of the instance variables.

The if statements, which check numberOfDice and sidesPerDie , are testing the parameter variables; the statements this. Such a statement can cause a very hard to locate bug! Another way around this whole "name conflict" problem is to change the parameter names; e. But, it is often the case that a well chosen name for an instance variable is replicated as a parameter name, because it captures exactly the right description; in such cases we must understand name conflicts and use this to resolve them.

To help avoid confusion, some style guidelines for Java specify that every access to an instance variable should be prefixed by this. I'm still on the fence about this style rule. The second SimpleDiceEnsemble constructor has a much different form. First, it has no parameters; second, it does not throw any exceptions this information is all specified in the constructor's header.

Note that because there are no parameter names in this constructor, so there are no name conflicts; therefore, we can use the instance variables directly with the this. But Java provides an even simpler way to define this constructor even if it requires us to learn a new language feature: This is a common pattern, where one general constructor with many parameters is used by one or more special constructors with fewer parameters to do the initializations.

Note that if we needed, we could add more statements to the constuctor AFTER this one here, none are needed. But the second constructor could be simplified to contain nothing in its body, because now when the instance variables are declared, they correctly represent two, six-sided dice.

Thus, constructors act as middlemen: Because instance variables are private , they can be initialized only in the declaration themselves, and reinitialized by a constructor defined inside the class. First, it cannot construct a rational value with a denominator or zero, is if the parameter has this values, it throws an exception. For all other numerators and denominators, it stores values according to the following rules.

The parameters are examined and changed as needed in all but the last two statements; at the end, this. Note the call to the method gcd , which is a static method defined in this class. Any non- static method can call a static method. Recall that we can declare blank final local variables. We can also declare blank final instance variables, but we must follow and additional constraint. Java allows us to declare an intance variable final and not initialize it in its declaration the definition of blank final But, we must initialize this variable in EVERY constructor that we write, otherwise the Java compiler will detect and report an error.

Of course, the Java compiler will ensure that we never try to assign a second value to any final variable, including final instance variables. Method bodies follow the same rules as constructor bodies, in terms of their use of parameter variables, local variables, and instance variables and in terms of this , variable name conflicts, etc. In fact, when we illustrate the call frame for a non- static method, it will show an implicit parameter named this and we will see how this parameter gets initialized by an implicit argument when such a method is called.

We cannot tell just by looking at a method header whether it defines an accessor or a mutator we must look at the method body or Javadoc. Yet, this is a fundamentally important piece of information about any method. Often, one can tell which it is by the name of the method: Also, void methods are almost always mutators: It is defined as follows. The roll method has no parameters; it declares two local variables firstThrow and nextThrow that it uses to change the rollCount , pipSum , and allSame instance variables Methods often have few or no parameters, because they primarily operate on the instance variables of an object.

The pips showing for each die are computed by the randomDie method, which We will examine later. Let us see how to hand simulate a call to this method by using a call frame. Pay close attention to how this , the implicit parameter, is initialized by the implicit argument.

The implicit parameter this appears in every non- static call frame; roll declares no explicit parameters. In this case, the call was dice.

This method then examines and changes the instance variables in this object, as well as the local loop index variable i. Hand simulate this code, again assuming randomDie returns 3 when it is called the first time and 5 the second. Note that by writing this. As stated above, even if we wrote just rollCount , because there are no name conflicts, the meaning of using this variable is exactly the same as this. Notice too the call to this. Generally, non- static methods inside a class can call other non- static methods in that same class, to help them accomplish their task on an object.

As in the case of instance variables, writing randomDie has exactly the same meaning here: The randomDie method must be able to access the sidesPerDie instance variable to compute a random roll of a die with that many sides. In the actual code for SimpleDiceEnsemble , this is used only where necessary.

Finally, the return statement returns the reference stored in this: The SimpleDiceEnsemble class defines many accessor methods, two of which are shown below. The forms of many of these methods are actually quite common: Note that the second method first checks that the pipSum instance variable actually stores a computed value before returning it; if the dice have not yet been rolled, it throws the IllegalStateException: The Rational class is immutable.

All its methods are accessors, although many construct and return values of primitive types or references to new Rational objects the result of computing on the state s of old one s , just as many String and BigInteger methods do.

In the Rational class, I have adopted the style of always using this. The second method returns whether or not a the object the method is called on, and b the object the method is passed as a parameter, are equal. Note that if we did not store these objects canonically, then this method would not work: We illustrate this method call by the call frame below. Notice that the implicit parameter, this , refers to the object that a refers to: Again, there is nothing special about the parameter named other ; we can name this parameter anything we want.

If we called b. This method call returns a result of false , because although the numerators are the same, the denominators are different. The return type of Rational means that this method returns a reference to an object that is an instance of the Rational class. In the abs method, we return a newly constructed Rational whose numerator is non-negative all denominators are already positive. The add method constructs and returns a new Rational object, whose state is the sum the states of the object that this method was called on and the object passed as the explicit argument.

In this add method, we return a newly constructed Rational whose numerator and denomiator are computed according to the standard algorithm for adding rational values. Note that the code in the complicated constructor for this class will automatically reduce the results to lowest terms. If we call x. Because this method returns a reference to a Rational object, we can cascade our method calls. If we wanted to compute the sum of the objects all three variables refer to, we can write x.

We can also write x. Each of these classes include a toString method that returns a String catenating together all the state of the object which is used mostly for debugging purposes.

Such toString methods are often easy to write; examine them. There are two kinds of special methods that we examine here briefly: Both kinds occur in classes that we will write, but they do not occur frequently.

First, sometimes a class will define private methods. Such a method is callable only from other methods defined in that class, not from any methods outside the class to use. Typically, private methods are small helper methods; they are useful for the implementor of the class, but not useful or dangerous for someone outside the class; like many methods, they hide some details. The SimpleDiceEnsemble defines the randomDie method, which uses a random numuber generator to simulate throwing one die.

The roll method has two calls to this one: The static method random defined in the Math class always returns a double result in the semiopen range [0,1 ; the expression transforms this value into an int between 1 and sidesPerDie , with each value equally likely to occur.

Second, sometimes a class one with a constructor will define static methods, either public or private. The Rational class defines the prompt method as public static.

The console interaction would look like Enter x Enter numerator: Thus, it is much simpler and easier to use this method if it is static. The Rational class also defines the gcd method as private static. Because this method is defined in the Rational class, we can call it as either gcd numerator,denomiator or as Rational. Note that because this method is private , it cannot be called from anywhere but inside a constructor or method defined in this class.

Finally, notice that the randomDie method cannot be static. That is because it must refer to the instance variable sidesPerDie ; static methods can refer only their parameter variables and local variables see prompt and gcd.

The fact that we can call static methods without objects means that they have no guaranteed access any object's instance variables. Of course, we could have rewritten it as a static method if we added a parameter: There are two main uses of static fields. The first and foremost is a place to declare constants using the final access modifier that other classes can use.

This article is a part of the guide:

Main Topics

Privacy Policy

As you are writing your method section, keep a style guide published by the American Psychological Association on hand, such as the Publication Manual of the American Psychological Association. Take a rough draft of your method section to your university's writing lab for additional assistance.

Privacy FAQs

This is a great lesson on how to write a good method for scientific enquiries. The lesson plan is really detailed and there are various ways to run this activity. If you have the use of networked PCs you can use the Excel version too, which allows all you 3/5(2).

About Our Ads

Genres in academic writing: Research report methods. The method describes the steps that you followed in conducting your study and the materials you used in each step. Writing Methodology Allows Verification In science, you are (hopefully) never presenting a personal opinion or arguing for preconceived biases. The value of your work rests squarely on how well it conforms to the principles of the scientific method.

Cookie Info

One standard way to write methods is in the "natural" order: if the body of method b calls method a, then method a is defined before method b. For example, we might have the following program form For example, we might have the following program form. Randy Ingermanson is called “the Snowflake Guy” for this novel writing method that came about from publishing 6 novels, winning dozens of awards, and teaching at writing conferences. Ingermanson was a software engineer for many years, and found the creation of a perfect snowflake using a computer an interesting process of layering on basic.