CISC 370 Lecture Notes for Class No. 5, February 22, 2000

Course Home Prev Lect Next Lect Example Progs Exercise Solns
CoreJava Progs
Documentation
Gen'l Docs Java 2 APIs Java Glossary Term Proj Info

Graded Assignment #3

To be completed and handed in at the next lecture.
Reading:
Horstmann & Cornell, chap. 5 up to p. 182 - we will skip the material on the class Class and reflection for the time being. But do read pages 198-204.
Exercises:

1. Look at the code in the file $CISC370HOME/exercise-solns/debugging/PayRaise.java . Show two different ways to change this code (that is, the code in PayRaise.java and that for the the classes Name and Employee) so that it compiles and executes as intended. Discuss the pros and cons of your two ways of "correcting" the code.

2. The following code appears in the file $CISC370HOME/exercise-solns/debugging/Complex.java . It is not a solution; it is a problem to be solved!

public class Complex{

    public static void main( String[] arg){
        Complex w = new Complex(1,2),
                x = new Complex(3,4);
        Complex y = w.add(x);
        System.out.println( "y = " + y );
         
    }


    Complex( double r, double i ){
        double rp = r;
        double ip = i;
    }
        
    Complex(){
        this(0,0);
    }

    public Complex add( Complex y){
        Complex ans = new Complex();
        ans.rp = rp + y.rp;
        ans.ip = ip + y.ip;
        return ans;
    }

    public String toString(){
        return "(" + rp +"," + ip + ")";
    }
        
    /**
     *  Instance variables
     */

    private double rp,
                   ip;
}
        
When compiled and executed, it produces the result
y = (0.0,0.0)
instead of the expected
y = (4.0,6.0)
Give the correct code and explain what is incorrect about the existing code. You may want to copy the file and insert some debugging output to help you track down the errors.

To prepare programming assignments for submission, do the following for each exercise.

script	        // Produces a file named typescript
whoami 
date 
pwd 
cat *.java 
javac *.java     // mainFile should be the name of the file containing
java mainFile    // your main() method
exit		 // to exit script

Now print the typescript file for submittal at the beginning of lecture.

Today's Lecture Topics

  1. A Delaware logo, a solution to homework #1 .

  2. A question from the last lecture: When we were discussing overloading equals(Object other) for the class Name, we were having to cast the parameter other to a Name in the code firstName.equals( ((Name)other).firstName). Joe Alcaqua asked, "Why not make the parameter type Name instead of type Object thereby overloading equals() instead of overriding it. Here is an example of the kind of problem that can arise if you overload instead of override. This problem occurred from use of the class java.util.Vector. This class is discussed in Chap. 5 of Horstmann & Cornell. A Java vector is a kind of dynamically extendable array that stores items of type Object. It is this latter feature that causes the problem if equals() is not implemented properly.

  3. Some additional questions that have arisen since the last lecture.

    (i)A number of persons still do not have the CLASSPATH variable set correctly. Here is a test that you can perform on strauss to double check this setting. For windows, do the tests on p. 709 of the textbook.

    Copy the file ~caviness/Class/CISC370-00S/CoreJavaBook/v1ch3/LotteryOdds/LotteryOdds.java to your directory. Make sure the file is named LotteryOdds.java after you copy it. Then do

             javac LotteryOdds.java
             java LotteryOdds
             
    If the program fails to compile or execute you do not have the CLASSPATH set correctly.

    (ii)Consider the following simple program. It does not compile - why?

         import corejava.Console;
    
    class T{
        public static void main( String[] arg ){
            System.out.print("Type a word and a number: ");
            String word = Console.readWord();
            double number = Console.readDouble();
    
            System.out.println("The word read was: " + word);
            System.out.println("The number read was: " + number);
        }
    }
            
    There is a lesson here about the design of public interfaces for classes, namely that if the methods in an interface do no behave in a consistent fashion it can be very confusing to the users.

  4. The accessor attributes public , private , protected , and package protection. (These four diagrams are adapted from the text On To Java by P. Winston and S. Narasimhan.)

  5. The class Object and three methods needed by most classes: toString(), equals(), and sometimes clone(). What exactly does the Object version of equals do? Let's look at the code. On Strauss all the JDK source code is in the directory /usr/jdk1.2.2/src/. The class Object is in the package java.lang.*. Thus, we want to look in the directory /usr/jdk1.2.2/src/java/lang. In the latter directory, we want to look at the file Object.java. Open the file with an editor and search for the clone() method.

  6. The class Complex . Note how toString(), equals(), and clone() are implemented.

    toString() returns a string representation of the complex number in the following format: Complex:(rp,ip). It is usual for toString to include the class name in its output. This overrides Object:toString() which just prints the class name and and the address of the Complex object.

    equals() checks that the real and imaginary parts of the two complex numbers are equal. It must override Object:equals() that only checks the pointers to the two objects.

    Since a Complex object contains no pointers, the bit-by-bit copy done by Object:clone() is sufficient. However, before we can use Object:clone() two things must be done.

    (a) In the class Object, clone() is declared protected so it cannot be used casually by other user programs - only by members of its own package and by classes derived from the Object class. Thus, to use it, we must explicitly override the method clone() and make it public. Since the class Complex is (implicitly) derived from the class Object, any method in Complex can use the protected methods from the class Object. So our new version of clone() simply calls the version of clone() from class Object with the code super.clone(). super is a Java reserved word the refers to the ancestor of the current class.

    (b) All classes that implement the clone() method must be tagged by saying that they implement the Cloneable interface. This is done on the first line of the class Complex definition by the code public class Complex implements Cloneable.

    clone() is not always needed. If the class has no setter methods so that class objects are immutable, a clone method is not normally needed. This would be the case for the class Complex if we eliminated the methods setRealPart() and setImagPart().

    Finally, notice the static method read( InputStream ). It reads a complex number in the format (rp,ip) from an input stream. If the input stream is System.in, read() will take its input from the console by default. At this point you are not expected to understand the implementation for this method, but you will note the length of the code and draw the correct conclusion that Java does not (yet) have a nice I/O system for input/output like C++ does. However, console I/O is not as important in Java as it is in C++ since much I/O in Java is done via GUIs (GUI = Graphics User Interface).

Back to the CISC 370 homepage.

This page has been accessed times since 17 Feb 2000.

Corrections, suggestions and comments to Bob Caviness

Copyright 2000 B. F. Caviness