Java Review

The Java API

Java File I/O

•      This example uses three I/O class objects

–  File class constructor takes filenames (Strings)

–  FileReader class constructor takes an object of type File or type String

•   read( ) is a method of this class;

–   it reads character by character
–   It returns an int, the number of characters read, or -1 if eof

–  FileWriter class constructor also takes an object of type File or of type String

•   write( ) is a method of this class

–   Note how the end of file is detected

 

Java interfaces

•      An interface tells the client all they need to know to use a particular class in your program

•      It may contain public constants, the signature for public methods, and comments describing the methods

•      A class that implements the methods in an interface implements the interface.

•      One extremely common interface is the Comparable interface

–    It has only one method, the compareTo method that returns an integer.  For x.compareTo(y)

•    Returns a negative if x < y

•    Returns zero if x = y

•    returns a positive if x > y

 

Example interface

•      The interface may contain constants, methods, and comments

     public interface Comparable
      {  public int compareTo(Object rhs)  }

•      Implementing the interface
public class FullName implements Comparable
{   private String firstName, lastName;
   //  constructor and other methods go here

       public int compareTo(Object rhs)
       if (lastName.compareTo(((FullName)rhs).lastName)== 0)
              return firstName.compareTo(((FullName)rhs).firstName);
       else
               return lastName.compareTo(((FullName)rhs).lastName);

 

Type casts with interfaces

•      In the FullName class above, notice that the compareTo method takes an argument of type Object, even though we want to compare names

–    The signature must be identical to the compareTo method in the interface Comparable

•      Since the argument passed in to the method is of type Object, it must be cast to type FullName to make the comparison

•      You see this type cast three times in the method.

–    Make sure you understand how the parentheses must be, because the compiler will not give you much help if wrong.

 

Java’s Iterator Interfaces

•      A iterator is used to traverse a collection of data

•      In Java, type Iterator is an interface, not a class

–   A data structure class (like ArrayList or LinkedList) that needs an iterator must implement the Iterator interface

•      What does must be done to implement the iterator interface?

–   Answer:  its methods must be implemented

 

The Iterator interface

•      There are three methods in the Iterator interface

   boolean hasNext( )  Returns true if the iteration
   has more elements. 
Object next( )  Returns the next element in the
    iteration. 
 
void remove( )  Removes from the underlying
    collection the last element returned by the
    iterator (optional operation). 

•      A class that implements the Iterator interface must implement these methods 

 

Implementing the Iterator methods

•      The two classes you should be familiar with that implement the Iterator interface are:

–   ArrayList

–   LinkedList

•      Look at in a diagram how next( ) would be implemented for these two classes

 

The interface ListIterator

•      ListIterator extends Iterator (it is derived from Iterator)

–   This means it automatically contains the three methods above

–   It also contains other methods as seen in the Java API

 

Inheritance and composition

•      Composition is used when you use objects of one or more existing classes as data fields in a new class

–   Composition defines a hasa relationship between two classes

•      Inheritance is used when groups of objects have properties and behaviors in common

–   Inheritance is used when there is a isa relationship

 

Example of inheritance

Extending the class BufferedReader

•      Suppose we wanted to make input easier by extending the BufferedReader class

•      What would we like in this class

–   1) To be able to read integers directly with a method readint( )

–   2) To be able to read strings

•   Without declaring all the other objects & classes

•   Reading from a file or keyboard more similar.

 

How to make our subclass

•      First line of code for the subclass:

Class BetterBR extends BufferedReader

•      Our class now has all the instance variables and methods of the superclass

–   The main methods we are interested in are

–   The constructors

–  readLine() an inherited method, and

–  readint() a new method we must write

 

Constructors

•      The job of the constructor is to provide a valid initial state for the newly created object.

•      Because a BetterBR object is a BufferedReader object we need to call the BufferedReader constructor

•      Usually you do this this way

BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));

 

Calling the constructor

•      Usually you call the constructor this way:

BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));

•      When the class is a subclass, you invoke the constructor with keyword super this way:

public BetterBR( ) throws IOException

 { super(new InputStreamReader(System.in));}

•      This is the constructor for when you want input from the keyboard.

 

Constructor for input from a file

BetterBR(String fileName) throws IOException 

 {  super(new FileReader(fileName)); }

•      Notice the difference between this and the first constructor

–   This constructor has a String argument

–   The argument for the FileReader constructor is the String argument.

 

The readint( ) method

int readint() throws IOException         
{    String line;
        line = readLine( );
        return Integer.parseInt(line);  }

•      Since this is a subclass of BufferedReader, readLine is one of the methods, so can be called without an object

•      How to handle the problem of the end-of-file condition

–    When reading a string, could read until the value returned by readLine was null

–    With an integer, that will not work, since null is not an integer.

–    Up to user to identify the end of file with a marker.

 

The files to download to test the following program

            BetterBR.Java

            junk

 

The entire class, with test

import java.io.*;

 

public class BetterBR extends BufferedReader

{   public BetterBR() throws IOException     // default constructor

    {   super(new InputStreamReader(System.in));    }

   

    public BetterBR(String fileName ) throws IOException   //one arg

    {   super(new FileReader(fileName));    }

   

    public int readint() throws IOException 

    {   String line;

        line = readLine();

        return Integer.parseInt(line);

    }

/************************************************************/

 

    public static void main(String[] arg) throws IOException

    {

        int i;

        String s;

        BetterBR bbr = new BetterBR("junk");

        i = bbr.readint();

        while (i>= 0)  // drop out of loop with a negative number

            {   System.out.println("i = " +i);

                i = bbr.readint();

            }

        s = bbr.readLine();

        while (s != null)   // read until end of file

            {   System.out.println("s = " +s);

                s = bbr.readLine();

            }  // end while

        }  // end main

    }  //end class BetterBR

   

 

 

Abstract classes

•      An abstract class is a class that contains at least one abstract method

•      An abstract method is a method that is not implemented

–   It is the return type and signature only

•      The abstract class is used as a base class from which other classes are derived

–   The derived classes must implement the abstract methods

(or else they also are abstract)

 

Example of an abstract class

•      Suppose you want to have a family of classes of type Shape

–   Circle, rectangle, triangle, etc.

•      You would like to find the area of all these shapes.

 

Interfaces and Abstract classes

•      Both interfaces and abstract class can contain  method signatures.

–   But the method cannot be implemented in an interface, while it can in an abstract class

–   A class with at least one abstract method must be declared as an abstract class

•      Interfaces cannot contain private data members, while abstract classes can.

 

When to use interfaces & abstract classes

•      Use abstract classes for base classes that may implement some of the methods, and may contain some data members

•      Use interfaces for

–   consistency among method names, and to

–   separate interface from implementation.

 

Dynamic binding

•      Since an inherited object can have several types, the compiler cannot always know its type at compile time

•      So it may not know which version of an overridden method to call

–   Both the base class and the subclass (and the sub sub class) may have methods of the same name which are implemented differently

–   This is polymorphism

 

Static and dynamic types

•      An object’s static type is the type that appears in its declaration

–   The static type is fixed and determined when the code is compiled

•      An object’s dynamic type is determined by which class’s constructor is used to create the object

•      Examples:
Comparable myName = new FullName(“Anne”, “DeFrance”)

     Shape s1 = new Circle(5.0);

 

Programming tips

•      Write a test program before you implement a class

–   You can include  a test of a class as a main method

–   If the class is used to create objects in another class or program, the main method is ignored.