五、Writing methods
Classes and methods
• To date every class has had one method - main
– It is the starting point for an application
– These classes are called driver programs
• We have used (invoked) prewritten methods
– eg from the Math class: pow(), random()
– eg from the String class: toUpperCase(), charAt()
• We know how they work but we didn’t write them
• We also need to write general purpose methods
• Methods do things
• They are like an independent mini-program
• By giving a name to a series of statements a program is easier to read and debug
• In some programming languages they are called
• functions, procedures, subprograms, subroutines
• It is good programming style to provide methods for doing particular functions
• ie isolate the function in a method
• Sequence of events when a method is called:
– the program “jumps” to that method.
– the arguments in the call (if any) are copied into the method’s corresponding parameters.
– the method begins executing.
– when the method is finished, the program “returns” to the point at which the method was called.
– If there is a return statement, the value specified is returned also
A main method
public class Welcome
{
public static void main(String[] args)
{
System.out.println(“Ladies and gentlemen – welcome to the Snakepit”); System.out.println(“And we hope you enjoy the show”);
}
}
• If the first print line is to be reused, we could create another method (also static as called from the static method main, not by an object)
Like a telephone call
main() is the calling method
welcomeMessage() is the called or invoked method
• As the static called method is located in the same class
– Only the method name is required to call the method
welcomeMessage()
• If the static called method is located in another class
– The method name must be preceded by the class name and period
Math.pow(2,2)
Methods with parameters
• Recall the Math max method we have studied eg.
static int max(int num1, int num2)
• We could also write a max method
public static int max (int num1, int num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Void methods
• void methods do not return a value
• They do not have a return statement
– their return type is stated as void
• eg main method
public static void main(String[] args)
Passing one parameter
• Write a main method that
– prompts the user for their name
– calls a method displayString and passes the name to it
• Write a method displayString that
– accepts a String parameter and displays it
Overloading Methods
• Method overloading is using the same method name for multiple methods
• The header of each overloaded method must be unique
• The header includes
– the return type,
– the order and the number of parameters
public static double addNumbers (double a, double b)
public static double addNumbers (double a, double b, double c)
• The compiler must be able to determine which version of the method is being invoked by analysing the signature
Overloaded Methods
• The println method is overloaded:
println (String s)
println (int i)
println (double d)
• The following lines invoke different versions of the println method:
System.out.println ("The total is:“ + total);
System.out.println (total);
Data scope
• The scope or visibility of a variable (or constant) is the area in a program in which that data can be used (referenced)
• Local variables and Parameter variables
– are declared within a method and can only be used in that method.
– They are created on the line where they are declared and destroyed when the method is exited
Variable scope
• Blocks can be separate or nested but never overlapping
{
{
}
}
• When you declare a variable within a block you cannot access it outside the block – it ceases to exist
– A nested block is within the scope of an outer block
• The portion of a program where you can reference a variable is its scope
Scope of Local Variables, cont.
• The scope of a local variable declared in a for loop header is the for loop block
public static void correctMethod()
{
int x = 1, y = 1;
for (int i = 1; i < 10; i++) // i is declared
{
x = x + i;
}
for (int i = 1; i < 10; i++) // i is declared again
{
y = y + i;
}
}
A common mistake
• Declaring a variable in a block and then trying to use it outside the block
for (int i = 1; i < 10; i++)
{
x = x + i;
}
System.out.println(“the value of i = “ + i);
• This will cause a compilation error
• We pass parameters to methods because of scope
• The parameter num is passed to the cube method because the cube method cannot access it – it is out of scope
public class TestCube
{
public static void main(String[] args)
{
for (int num = 0; num < 6; num++)
System.out.println(num + “/t” + cube(num);
}
public static int cube(int x)
{
return x * x * x;
}
}
BlueJ Debugger
• Demonstrate BlueJ debugger (eg OddEven)
• A debugger is an essential tool for finding logic errors
• What functions does it provide?
– Setting breakpoints
• This stops program execution at this point and displays the code
• Click in the area to the left of the text in the text editor
– Stepping through the code
• Step line by line
• Step into a method
– Inspecting variables
• These are automatically displayed
六、Arrays and exceptions
Arrays
• An array is a simple but powerful programming construct
• Consider this cumbersome expression
avgSales = (janSales + febSales + marSales + aprSales + maySales + junSales + julSales + augSales + sepSales + octSales + novSales + decSales) /12;
• If the type of each field is identical we can create an array or list of values
• Instead of defining 12 variables, we define one and access it with an index
• An array stores multiple values of the same type
• That type can be primitive types or objects
• Therefore, we can create
• an array of integers
• an array of doubles
• an array of characters, or
• an array of String objects etc.
• In Java, the array itself is an object
• The scores array could be declared as follows:
int[ ] scores = new int[10];
• The type of the variable scores is int[] (an array of integers)
• ie. a new array object that can hold 10 integers
Bounds Checking
• Once an array is created, it has a fixed size
• An index used in an array reference must specify a valid element
• That is, the index value must be in bounds (0 to n-1)
• The Java interpreter will throw an exception if an array index is out of bounds
• Each array object has a public constant called length that stores the size of the array ie the number of elements
• It is referenced using the array name (just like any other object):
scores.length
Array Declarations
• The brackets of the array type can be associated with the type or with the name of the array
• Therefore the following declarations are equivalent:
double[] prices;
double prices[];
• The first format is more common
Initializer Lists
• An initializer list can be used to instantiate and initialize an array in one step
• Values are delimited by braces and separated by commas
• Examples:
int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114};
char[ ] letterGrades = {'A', 'B', 'C', 'D', 'F'};
• Note that when an initializer list is used:
– the new operator is not used
– no size value is specified
• The size of the array is determined by the number of items
Passing Array elements to Methods
• You can pass a single array element to a method in exactly the same way as you pass a variable
• The variables are local to the method and any changes to variables passed into methods are not permanent
– ie changes are not reflected in the main() program
• Arrays are objects
• Arrays are passed by reference
– the method receives the memory address of the array and has access to the actual values in the array elements
– the method can therefore change values in the array
Exceptions
• When a Java program performs an illegal operation,
– an exception happens
• Exceptions occur during program execution – not compilation ie errors the compiler cannot detect
• If a program has no special provisions for dealing with exceptions, it will behave badly if one occurs
– the program will terminate immediately
• Java provides a way for a program to detect that an exception has occurred and execute statements that are designed to deal with the problem.
Handling Exceptions
• When an exception occurs (is thrown), the program has the option of catching it.
• In order to catch an exception, the code in which the exception might occur must be enclosed in a try block.
• After the try block comes a catch block that catches the exception (if it occurs) and performs the desired action.
try
block
catch (exception-type identifier)
block
try
{
// one or more statements at least one of which may
// be capable of causing an exception
}
catch (exceptionName argument)
{
// one or more statements to execute if the exception
// occurs
}
• If an exception is thrown within the try block, and the exception matches the one named in the catch block, the code in the catch block is executed
• If the try block executes normally—without an exception—the catch block is ignored
ArithmeticException
• an illegal arithmetic operation is performed
• eg trying to divide by zero
int divisor = 0;
try
{
quotient = dividend / divisor;
}
catch (ArithmeticException e)
{
System.out.println("Error: Division by zero");
}
NumberFormatException
– Occurs when an attempt is made to convert a string that does not contain the appropriate characters
– eg trying to convert alpha characters or spaces to an integer
try
{
int num = Integer.parseInt(“doh”);
}
catch (NumberFormatException e)
{
System.out.println("Error: Not an integer");
}
Valid data entry
• A robust program will not allow erroneous data input by a user to cause it to crash
• If invalid data is entered it needs to be caught
• Put the try and catch blocks in a loop
• Allow the user multiple attempts to enter a valid data
String numStr;
int num = 0;
while (num < 1 || num > 100)
{
numStr = JOptionPane.showInputDialog
("Enter an integer between 1 and 10");
try
{
num = Integer.parseInt(numStr);
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Not an integer");
}
}
七、Writing instantiable classes
Two types of Class
• Those not as templates for objects (no instances of these classes will be created):
– Driver programs ie a class that contains a main method
– Collections of constants and/or methods eg. Math
• Those used for defining and creating objects
– instantiable classes
– ie we can create instances of these classes (objects)
• An instantiable class is a blueprint used to create objects
– many things or objects are made from a pattern or template
• It is a generalised case that defines what data we need to define a specific case (an object )
– eg a car
• What generalised data might we use to define cars?
• What data would define a specific car object eg my car?
– What about a book, a triangle, a student, a room…
• A class also defines methods to allow us to change objects
• The String class is used to define String objects
String str;
• Each String object contains specific data (its state)
str = “a meaningless string”;
• Each String object can perform pre-defined methods
String newStr = str.toUpperCase();
• Suppose we wanted to write a program that simulates the flipping of a coin
• Think of a coin object as an actual coin
• We could write a Coin class to define coin objects
• How would we define the state (data) of a coin?
• If you are just flipping a coin, what data would you need to define a coin?
• What method (or behaviour)could you apply to the coin?
• The state of the coin is its current face (heads or tails).
– How would you represent the face of a coin?
• Because the state of an object can change, it is defined by variables ..known as instance variables
– Each object is an instance of the Coin class
• The behaviour of the coin is that it can be flipped.
– the behaviours of objects are defined by instance methods
– How would you represent flipping a coin?
• Note that the behaviour of the coin might change its state
Constructors
• A constructor is a special method that contains instructions to set up a newly created object
• When writing a constructor, remember that:
– it has the same name as the class
– it is syntactically similar to a method
– it does not return a value
– it has no return type, not even void
– it often sets the initial values of instance variables
– it is invoked by the keyword new
Passing data to a Constructor
• The Coin or Date constructors did not require any data to be passed to it them create objects
– the instance variables were initialised by existing data
• Often constructors require data to initialise objects uniquely
• Note: if no constructor is provided Java will provide a default one to create an object
– instance variables will be set to default values
• Consider an Account class for a bank
• What instance variables could define each object?
• What methods would the class require?
• When setting up a new account (ie creating an Account object), it would be useful to create it and initialise the instance variables appropriately
• The constructor accepts parameters just like methods
Visibility (or Access) Modifiers
• Usually the declaration of
– an instance variable,
– a constructor, or
– an instance method
begins with an visibility modifier (public or private)
• A visibility modifier determines whether that entity can be
– accessed by other classes (public) or
– accessed only by methods within the class itself (private)
• The most common arrangement is for instance variables to be private
• This makes access to them available only by methods within the class
private int face;
• The only access to face therefore will be through the instance methods provided in the Coin class
private int face;
Access to instance data
public void flip () // Flips the coin by randomly choosing a face
{
face = (int) (Math.random() * 2);
}
public int getFace () // Returns true if the current face of the coin is heads
{
return face;
}
• The driver program cannot access the face variable directly
Visibility – constructors and methods
• Constructors and methods that provide the object's services are usually declared with public visibility
– Then they can be invoked by clients
• So any program that uses a Coin object can invoke the following:
public Coin() //constructor
public void flip() //method
public int getFace() //method
Information hiding
• By limiting access to the variables in a class
– making them private
• If access to a variable is needed outside the class,
– provide a method that returns the value of the variable
– and/or a method that changes the value of the variable.
• Methods that modify the variables can check the validity of the new values
Encapsulation
• An encapsulated object can be thought of as a black box
• Its inner workings are hidden to the client, which only invokes the methods
• Most documentation has been removed from the programs shown on the lecture slides to conserve space
• Do not treat these programs as being sufficiently documented – they are not!
• Now that you are developing methods it is particularly important that every class and every method is documented, as in the text
//-----------------------------------------------------------------
// Sets up the coin by flipping it initially.
//-----------------------------------------------------------------
public Coin ()
{
flip(); }