Download Java 211 – Lecture 3

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java 211 – Lecture 4
Mendelsohn
We will spend this week focusing on classes. Whatever we do not cover in this lecture
will be completed next week.
Let’s begin our practice by designing a ‘Die’ class ourselves…
Another example:
Account.java
BankAccounts.java
Strings
Strings are not primitive data types, they are in fact, objects. This means that they can
invoke methods. However, unlike many other objects, strings only have one field that is
of significance to us, an array of characters. (We will discuss arrays).
Some commonly used methods that can be invoked by a string object include:
- equals (returns a bool)
- length (returns an int)
- toLowerCase (returns a String)
Concatenation
There is a special operator, represented by the ‘+’ sign, that can be used to
concatenate two or more strings together. This is why you can have two strings
inside a println statement joined by + that will then be represented as a single string.
The second string is appended on to the end of the first string.
- Also, strings can be concatenated with numbers
- If the two operators on both sides of a + are numbes, then addition is performed.
Otherwise, concatenation is performed. You can also control behavior by using
brackets.
- See Facts.java
Escape Sequences
Sometimes we want to output special characters such as quotation marks or \ signs or
newlines, etc. in our strings. Because these characters can interfere with our source
code, we need a way of indicating to the compiler that these are special characters and
must not be treated in their usual way. The technique is to precede these characters
by a ‘\’ character. A partial list of escape sequences is given in figure 2.2 (p. 58) of
your book.
- See Roses.java
Since we have established that Strings are objects of a class called ‘String’, lets take a
quick look at some of the methods of that class by checking out the String API.
Creating Objects
When you declare an object, you are only creating a reference to the object. No object
actually exists yet. That is, the identifier name only stores an address in memory. To
actually create a new object, you must use the ‘new’ operator.
String quote;
//creates a reference to a string
quote = new String(“Planes are great.”); //creates a string object
Most often, the above two lines are notated in a single shorthand line:
String quote = new String(“Planes are great.”);
You have no doubt noticed that we have frequently been cretaing strings as follows:
String quote = “Planes are great.”;
This works only because string objects are so frequently used, that the Java developers
created a shortrcut for creating and initializing these objects.
Packages
A package is a group of classes grouped together under a name.
- All of the standard classes in Java are contained within packages. For example,
the classes Math, String, and System are all contained in a package called
“java.lang”
One of the benefits of Java is the tremendous number of classes written by third party
groups, (By ‘third-party’ we mean groups not necessarily affiliated with Sun, the
creators of Java). Even the String class is not a de-facto part of the Java standard.
However, its use is so obviously necessary for the development of even rudimentary
programs, that this class gets shipped along with all standard implementations of Java.
There are several similarly useful classes that you will automatically receive when you
download the SDK. These classes make up the Java standard class library. The
functionality provided by these libraries include mathamatical capabilities, networking
capabilities, security functionality, applets, graphics, and others.
A group of related classes is usually bundled into a package. Some packages in the Java
standard class library include: java.applet, java.awt, java.math, java.lang,
java.security, java.sql
In order to use a class, we must first import it into our program. For example, to use the
String class, we would need to import it from the java.lang package:
import java.lang.String;
Similarly, if we wanted to use the System class, we would import it using:
import java.lang.System;
Alternatively, we could import all of the classes in java.lang by issuing:
import java.lang.*;
As we’ve just discussed, the String class is part of the java.lang package. So is the
‘System’ class. However, notice that we did not have to use the ‘import’ statement
discussed in the previous paragraphs. The reason is that since these classes are used so
frequently, the ‘java.lang’ package is automatically included for us in every Java
program. It is as if the line:
import java.lang.*;
is invisible, but present in every program.
The ‘*’ after java.lang says to import all classes from the library (package). If we only
wanted to use, say, the String class, we could instead type:
import java.lang.String;
But again, this is a moot point since as we said, the entire java.lang package is imported
into every Java program.
Let’s take a look at some other useful classes:
See:
- RandomNumbers.java (API Specification for Random class)
- Price.java
- CircleStats.java //makes use of the textbook’s keyboard class…
Notice how in the CircleStats.java program there is an import statement that says:
‘import cs1.Keyboard;” . The problem here is that this package is not part of the
Java standard library. Since we are making use of a non-standard library, we must have a
copy of this package to put somewhere, where our compiler can make use of it. The
easiest way to do this is to copy the ‘cs1’ directory into the same folder as the source file.
- This directory makes up the package. That is, to create a package, you simply
take a number of related classes, and put them in a directory of whatever name
you choose. The name you give to your directory becomes the name of the
package.
Static Methods: Invoking Without Instantiating
Typically, to access a field or invoke a method, we need to specify an object. However,
there is one exception: ‘static’ fields or methods. A method or field that is static can be
accessed without requiring a calling object.
Recall that whenever we specify a member variable (field) or a method of a class, we
must specify an object to invoke the method (or on which to alter a field). For example, I
can’t simply call the ‘toUpperCase()’ method of the String class without specifying a
String object. However, there are some methods which can be invoked without
specifying an object. These are called ‘static’ methods.
For example, the Math class has a method called Random() (very similar to the Random
class we saw in the java.util package). As discussed earlier, it is not uncommon in
programming to want to get a random number from the program. If this method was not
a static method, I would have to do the following:
Math num = new Math();
double n = num.random();
By the way, the line Math num = new Math(); is not even allowed in Java. It is
not possible to instantiate objects of type Math. (The explanation of why is beyond the
scope of this lecture).
In other words, we had to create a Math object for no other reason than to generate the
random number we wish to put into ‘n’. We have no plans to use this object again. For
this reason, the developers of the class made ‘random’ a static method. This means that
you do NOT need an object to invoke the method. Simply providing the name of the
class is sufficient:
double n = Math.random();
In fact, in the example earlier, the statement Math num = new Math(); is illegal
since you cannot instantiate a static class.
This is the same thing we saw with the textbook’s Keyboard class earlier. To invoke any
of the methods such as ‘readInt()’, ‘readString()’ etc, we need only specify the class
name: String s = Keyboard.readString();
Look at the header for this method:
static String readString() { …
- See Echo.java
Reading Input into a Dialog Box
String s;
s = JOptionPane.showInputDialog(“Enter a number: “);
 The above line will draw a dialog box on the screen and prompt the user to “Enter a
number: “.
 Whatever value the user types into the dialog box will be stored inside the string ‘s’.
Note how we said that the information entered by the user is entered as a string. So if we
wish to, say, get an int from the user, we must somehow convert the string (currently
stored in the variable ‘s’) to an int. There is a method called ‘parseInt()’ that will
accomplish just that. This is a static method, and can be found in a class called ‘Integer’.
(Note: The Integer class is in the java.lang package, so we do not need any import
statements). Here is the code again…
String s;
int num;
s = JOptionPane.showInputDialog(“Enter a number: “);
//The above line will open up a dialog box and
//store the value entered as a string into the
//variable ‘s’.
//Don’t forget to import the package containing
//JOPtionPane!
num = Integer.parseInt(s);
//1. Converts the value stored inside ‘s’ into an integer.
//2. Places that value into num.
Assignment: A big part of learning Java is learning how to make use of the many classes
available to you. Take a look at and experiment with the DecimalFormat class that we
made use of in the CircleStats.java program earlier. Try to find the API of the class from
the link provided here. You can do a search in the ‘All Classes’ frame (lower right).
print and println – and the ‘System.out’ object
Now that we have discussed objects somewhat, we can begin to demystify the odd
‘System.out.println(String)’ statement.
- ‘System’ is a class that contains a few useful fields (properties) and methods.
One useful field of the System class is an object called ‘out’.
- The ‘out’ is an object that by default, refers to the monitor screen.
- Because the object called ‘out’ is a ‘static’ object, we can access it directly
without using an object of type System.
- The data-type of the ‘out’ object is ‘PrintStream’.
- PrintStream has several useful methods, two of which are ‘println’ and ‘print’
- The ‘println’ method is a method that belongs to (exists in) a class called
‘PrintStream’. That is, any object of type ‘PrintStream’ can call the ‘println’
method.
- The difference between ‘print’ and ‘println’ is that println inserts a newline
chracter into the output stream at the end of the string.
- See Countdown.java
Abstraction
- Separate interface from the implementation. That is, someone who uses a class
should not have to know anything about how the class does its work.
- For example, when you call a class’ method, you don’t need to know anything
about how the method works, you only need to know what it does. To drive a car,
you need only know how to turn it on, turn it off, steer, break, and accelerate.
You don’t need to know anything about how these things work, you need only
know the proper way of ‘invoking’ the functionality. (E.g. Turn the key in the
ignition to start the car).
- The advent of automatic transmissions from manual transmissions is
analogous to ‘raising the level of abstraction’.
-
It is possible that some people may want or need to know more low-level details,
but our classes should be designed so that people who wish to remain blissfully
ignorant, can do so.
has-a Relationship
Some fields of an object can be other objects. For example, you may have an ‘Address’
class which contains information about a street, and telephone number. A ‘Person’ class
may have as one of its fields, an ‘Address’ object.
More on Constructors and the ‘has-a’ relationship
See BankAccounts.java, Account.java
Method Overloading
Often you would like to give the same name to two methods which are extremely similar.
For example, take the println method. This method takes a String and prints it out on a
line. Now what if you wanted a method that takes an ‘int’ and prints it out on one line.
Should you have to create a method with a new name? Fortunately, Java supports a
technique called method overloading whereby you can have two or more methods with
the same name. The requirements are as follows:
- the method must differ in the number of arguments OR
- the method must differ in the type of (at least one of) the arguments
The println method has been overloaded to take all kinds of arguments:
println(String s), println(int i), println(double d), println(char c), println(boolean b)
Constructor methods are primary candidates for overloading. For example, how might
we overload the constructors for the Account class?
Example: Let's say that you have a function called 'average' which calculates the
average of 2 numbers. At some other point, though, you may wish for a function
that calculates the average of three numbers. The 'overloading' mechanism allows
you to create 2 functions, both called 'average'. However these two functions will
take different numbers of formal parameters. This is how the compiler will be
able to distinguish between them.
average(3, 7);
//returns 5
average(3, 7, 2); //returns 4
Example: Another example is the arithmetic operator (+, -, etc). These are
defined on all of the number types, that is, long, int, float, double and long double. This
means that for each type there has to be a separate function definition.
Introduction to Overloading
Maybe we want to write a function to average two numbers:
double average(double n1, double n2)
{
return ((n1 + n2) / 2.0);
}
and we might also need a function to average three numbers:
double average(double n1, double n2, double n3)
{
return ((n1 + n2 + n3) / 3.0);
}
We can give this second function the same name, average, and at that point we have
overloaded the function name average.
How can the compiler understand which average we mean when we use it? It simply
checks the number of arguments and the type of the arguments and uses the definition
that matches what it finds. So whenever we overload a function it must be the case that
one of the following holds:


the number of arguments is different for each function definition ORthe type of one (or more) of the formal parameters must be different
i.e. we cannot have two function definitions with the same number and types of
arguments. This is true even if the functions differ in the type of their returned value.
Example: these together are illegal:
int someFunction(double n1, double n2);
double someFunction (double num1, double num2);
We really must be careful about the types that we give functions. If there are two
definitions out there for a function and we accidentally give the wrong types for the
arguments, the compiler may pick the wrong definition. Many other programming
languages do not support function overloading..
Java also does automatic type conversion for functions. If a function requires an
argument of type double, and you pass it an argument of type int, Java will automatically
convert the int argument to a double. However, overloading can interfere with this
conversion, so you must be very careful about the types of arguments that you pass to
function calls.
Summary: Overloaded functions must have different numbers or different types of formal
parameters. Also note that you cannot overload functions by simply changing the type of
the value that is returned.
A very common use of overloading is with constructors of classes. Recall that
constructors are special methods in classes that are called whenever the class is
instantiated.
StudentRecord marc = new StudentRecord();
Again, see Die.java
Assignment: Look at the StringTokenizer class and play with it. This type of
functionality is extremely useful in a number of situations. For example, it can be used to
parse forms returned from a web page to keep malicious users from entering operating
system commands.