Page tree
Skip to end of metadata
Go to start of metadata


week8-examples-2016-11-06.zip

Review: toString() versus hashCode()

class CompareToStringWithHashCode
{
    public static void main(String[] args)
    {
        Object myObject = new Object();
        System.out.println(myObject.toString());
        System.out.println(myObject.hashCode());

        String myString = "hello";
        System.out.println(myString.toString());
        System.out.println(myString.hashCode());

        Object[] myObjectArray = new Object[3];
        System.out.println(myObjectArray.toString());
        System.out.println(myObjectArray.hashCode());

        String[] myStringArray = new String[3];
        System.out.println(myStringArray.toString());
        System.out.println(myStringArray.hashCode());

        int[] myIntArray = new int[3];
        System.out.println(myIntArray.toString());
        System.out.println(myIntArray.hashCode());

        double[] myDoubleArray = new double[3];
        System.out.println(myDoubleArray.toString());
        System.out.println(myDoubleArray.hashCode());

        boolean[] myBooleanArray = new boolean[3];
        System.out.println(myBooleanArray.toString());
        System.out.println(myBooleanArray.hashCode());
    }
}

interface - more abstract than an abstract class

Often, an interface is about a capability, such as the ability to act like something or look like something.

class LeafySeadragon extends Seahorse implements SeaweedLike

class Anglefish extends Fish implements FoodLikeLure, implements Bioluminescence

class DazzleCamouflageShip extends Ship implements ZebraLike

In 1918, the British Navy attempted to prevent German submarines from knowing a ship's orientation and thus be less able to perceive and anticipate its direction of travel.

 

class SnowBus extends Bus implements Snowmobile

class SnowCoach extends Bus implements Tank

class SeaPlane extends Airplane implements Floatable

For places without an airport

A class can implement any number of interfaces

class Textbook extends Book implements Taxable, TradeInable, BuyUsed, Ebookable

Hand interface

Consider the interface of Hand, where the coordinated effort of five digits enable locomotion.

elephant

bat

dolfin

frog

Interface use case and rules

Whereas the use case for an abstract class is to implement some functionality and allow the subclass to implement additional functionality, an interface is not allowed to provide any functionality whatsoever. It is a pure specification to guide the developer who implements the interface.

Rules for Interface defintions:

  • a class can implement zero, 1, or many interfaces
  • an interface can specify zero, 1, or many methods
  • an interface can declare zero, 1, or many fields

Rules for a class implementing an interface:

  • a class can implement zero, 1, or many interfaces
  • implement all the methods of the interface, and declare them public
  • fields inherited from the interface are implicitly public, static, and final

implementation syntax

interface Shape
{
    double calculateArea();
    double calculatePerimeter();
}
class Circle implements Shape
{
    public double calculateArea()
    {
        return 0.0;
    }
    public double calculatePerimeter()
    {
        return 0.0;
    }
}
class InterfaceImplementedDemoTest
{
  public static void main(String[] args)
  {
  }
}

use case for an empty interface

http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html

StaffMember kirk implements beamable;

Star Trek can beam staff members, but not lunch, nor the entire Spaceship Enterprise. Lunch and the Spaceship do not implement beamable.

implementation by two classes

interface Shape
{
    double calculateArea();
    double calculatePerimeter();
}
class Circle implements Shape
{
    double radius;
    Circle(double radius, boolean isCircle)
    {
        this.radius = radius;
    }
    public double calculateArea()
    {
        return Math.PI * (Math.pow(this.radius, 2));
    }
    // perimeter analogous to circumference
    public double calculatePerimeter()
    {
        double circumference = 2 * Math.PI * this.radius;
        return circumference;
    }
}
class Rectangle implements Shape
{
    double length, width;
    Rectangle(double l, double w)
    {
        this.length = l;
        width = w;
    }
    public double calculateArea()
    {
        return length * width;
    }
    public double calculatePerimeter()
    {
        double perimeter = 2 * (length + width);
        return perimeter;
    }
}
class InterfaceImplementedDemo
{
  public static void main(String[] args)
  {
      Rectangle myRectangle = new Rectangle(3,3);
      System.out.println("myRectangle perimeter is " + myRectangle.calculatePerimeter());
      System.out.println("myRectangle area is " + myRectangle.calculateArea());
      Circle myCircle = new Circle(3,true);
      System.out.println("myCircle circumference is " + myCircle.calculatePerimeter());
      System.out.println("myCircle area is " + myCircle.calculateArea());
  }
}

Runnable interface

Let's implement the Runnable interface - http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html

class MyThread implements Runnable
{
  int count;
  Thread myCustomThread;
  // Construct a new thread.
  MyThread(String name)
  {
    myCustomThread = new Thread(this, name);
    count = 0;
    myCustomThread.start(); // start the thread
  }
  // Begin execution of new thread.
  public void run()
  {
    System.out.println(myCustomThread.getName() + " starting.");
    try
    {
      do
      {
        Thread.sleep(500);
        System.out.println("In " + myCustomThread.getName() +
                           ", count is " + count);
        count++;
      } while(count < 10);
    }
    catch(InterruptedException exc)
    {
      System.out.println(myCustomThread.getName() + " interrupted.");
    }
    System.out.println(myCustomThread.getName() + " terminating.");
  }
}
class InterfaceForThreadDemo
{
  public static void main(String[] args)
  {
    System.out.println("Main thread starting.");
    MyThread mt = new MyThread("Child #1");
    do
    {
      System.out.print(".");
      try
      {
        Thread.sleep(100);
      }
      catch(InterruptedException exc)
      {
        System.out.println("Main thread interrupted.");
      }
    } while (mt.count != 10);
    System.out.println("Main thread ending.");
  }
}

single inheritance but multiple interface implementation

interface Taxable
{
    boolean isSalesTaxRequired = true;
    double calculatePriceWithTax(int price);
}
interface Shippable
{
    String deliveryServiceProvider = "U.S. Postal Service";
}
interface Returnable
{
    int timeLimit = 30; // days before returning item
}
class InventoryItem implements Taxable, Shippable, Returnable
{
    int itemID = 0; // increment this value
    public double calculatePriceWithTax(int price)
    {
        double tax = price * .1;
        return tax + price;
    }
}
class BoseRadio extends InventoryItem
{
    BoseRadio()
    {
        System.out.println("this.itemID++ " + this.itemID++);
    }
}
public class MultipleInterfaceImplementationDemo
{
   public static void main(String[] args)
   {
      System.out.println("An interface field is public, final, and static " + BoseRadio.isSalesTaxRequired);
      BoseRadio br1 = new BoseRadio();
      System.out.println("br1.itemID++ " + br1.itemID++);
      System.out.println("Are we required to collect sales tax when shipping this item? " + br1.isSalesTaxRequired);
      System.out.println("Total with tax is " + br1.calculatePriceWithTax(100));
   }
}

abstract class and interface in combination

/* Illustrate that an abstract class can perform
   partial implementation of an interface */
interface TwoMethods
{
   void method1();
   void method2();
}
abstract class PartialImplementation implements TwoMethods
{
   public void method1()
   {
      System.out.println("PartialImplementation is an abstract class that hereby implements method1");
   }
   // leave the implementation to the subclass
   public abstract void method2();
}
// class FinishImplementation extends PartialImplementation implements TwoMethods {
class FinishImplementation extends PartialImplementation
{
   public void method2()
   {
      System.out.println("FinishImplementation is a nonabstract class that implements interface method2.");
   }
}
class ImplementSome
{
   public static void main(String[] args)
   {
       //PartialImplementation pi = new PartialImplementation();
       // create an object and call methods on it
       FinishImplementation fi = new FinishImplementation();
       fi.method1();
       fi.method2();
  }
}

interface as type that instanceof supports and an array of an interface type

interface Science
{
    int BOILING_POINT = 100;
}
class FieldExperiment implements Science
{
    // write code to do something
}
class ScienceLab implements Science
{
    // write code to do something
}
class InterfaceArrayDemo
{
    public static void main(String[] args)
    {
        Science[] myScienceArray = {new FieldExperiment(), new ScienceLab()};
        //Science[] myScienceArray = new Science[2];
        //myScienceArray[0] = new FieldExperiment();
        //myScienceArray[1] = new ScienceLab();
        System.out.println(myScienceArray[0]);
        if (myScienceArray[1] instanceof Science)
        {
            System.out.println(myScienceArray[1].getClass() + " is also a Science object.");
        }
    }
}

interface can have default methods and static methods

file with the interface definition

import java.time.*;
public interface InterfaceWithDefaultAndStaticMethods
{
  static ZonedDateTime getGMT()
  {
      ZonedDateTime currentDate = ZonedDateTime.now(ZoneOffset.UTC);
      return currentDate;
  }
  static String showString()
  {
    return "hello";
  }
  default double getDefaultAccountBalance()
  {
      return 0.0;
  }
  default boolean getTrue()
  {
      return true;
  }
}

file with the interface implementation

class Implementation1 implements InterfaceWithDefaultAndStaticMethods
{
}

file with main to demonstrate

class DefaultAndStaticMethodDemo
{
  public static void main(String[] args)
  {
    Implementation1 test = new Implementation1();
    System.out.println("The time in London is " + InterfaceWithDefaultAndStaticMethods.getGMT());
    System.out.println("The default account balance is " + test.getDefaultAccountBalance());
  }
}


packages and the file system

A package is a group of related classes. For example,

com.perforce.p4java.exception

which contains Exception classes for Perforce, such as

https://www.perforce.com/perforce/r10.1/manuals/p4java-javadoc/com/perforce/p4java/exception/ConnectionException.html

Note:

  • The convention of naming a package is by reverse URL, so that the package name is unique across the internet.
  • The name of a package represents a physical directory on the file system hard disk.
  • To allow your class with main to see the package directory, navigate one directory above the directory with the package files.

import keyword

The keyword import allows you to avoid having to type the fully-qualified name of a class.

import java.io.*;

package keyword

The package keyword allows you to declare that the classes in the current file belong to the specified package. This statement must be the first line in the file.

package funstuff;

To compile the source code file with the main method

javac directoryName/fileName

javac bicycle/PackageDemo.java

To run the bytecode

java package_name.class_name

java bicycle.PackageDemo

package example

This example anticipates next week, Lecture 9: Exception Handling and Introduction to java.lang.io, but it does give a fairly realistic use case for creating a package, which should contain a set of related classes.

Create a directory named color that contains the following two files.

/* USAGE:
Step 1: Compile one directory above the package directory.
    javac color/ColorGuess.java
Step 2: Run by invoking the fully-qualified class name.
    java color.ColorGuess
*/
package color;

import java.io.*;

public class ColorGuess
{
    public static void main(String[] args)
    {
        System.out.println("France, the United Kingdom, and the United States all have national flags with the colors red, white, and _______ " );
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try
        {
            String s = in.readLine();
            if (s.equalsIgnoreCase("blue"))
                System.out.println("Correct");
            else
                throw new ColorException("Incorrect answer.");
        }
        catch(ColorException ce)
        {
            System.err.println("Incorrect: "+ ce.getError());
        }
        catch (IOException e)
        {
            System.err.println("A problem occurred: "+ e.getMessage());
        }

        finally
        {
            try
            {
                in.close(); // avoid memory leak!
                System.out.println("This concludes the program.");
            }
            catch (IOException e)
            {
                System.err.print("Error message: "+ e.getMessage());
            }
        }
    }
}

This class anticipates next week, when we learn how to create a custom exception.

package color;
public class ColorException extends Exception
{
    private String errorString;
    public ColorException(String s)
    {
        this.errorString = s;
    }
    public String getError()
    {
        return this.errorString;
    }
}

Change directory using cd to be one directory above the color directory and

  1. Compile one directory above the package directory     javac color/ColorGuess.java
  2. Run the bytecode by invoking the fully-qualified class name     java color.ColorGuess

jar - the Java archive utility

IN THIS COURSE, PERFORM ALL THE STEPS USING A COMMAND LINE, SUCH AS MAC OS TERMINAL OR WINDOWS CMD.

A jar file is a Java Archive, that is, a single file that contains multiple files. The archive generally contains .class files.

The archive:

  • can combine many files and directories into a single deliverable
  • compresses the amount of disk space the files require
  • typically contains executable bytecode, that is, .class files, which can run without having to be uncompressed. In this sense, a .jar file is better than a .zip file.

An installer might copy a .jar file onto a client computer and update the PATH so that the application can easily be run.

An open source project can use a .jar file to ship source code.

Underlying the functionality is the package, java.jar.util, which contains the Jar class and the Manifest class

Examples

All three examples illustrate the implementation of an interface.

Location of mainJar Name
inside package directoryexample1.jar
above package directoryexample2.jar
no package directorydoctorjar.jar

How to create a .jar file

  1. Make sure your application meets the Homework specification and runs as expected.
  2. Create a manifest with a name like homework8-manifest.txt.
    The manifest file indicates which class has the main method, by beginning with a line that says Main-Class: HelloWorld , where HelloWorld represents the name of the class with main.
  3. Add two or three blank lines after the first line::

  4. Make sure all the .java source code files, the .class bytecode files, and the manifest file are in a single directory.
  5. At the command line, navigate to that directory and build the jar with the syntax:

    jar  cmf  manifestname.txt  jarname.jar  *

    For example:
    jar  cmf  myManifestForTheClassWithMain.txt  myJarFile.jar  *
  • jar invokes the jar utility
  • cmf means create ("c") a jar with the manifest ("m") by specifying the file ("f") on the command line
  • myManifestForTheClassWithMain.txt is the manifest
  • myJarFile.jar is the name of the jar, which normally ends in .jar to indicate that it is a jar file
  • the asterisk (*)  means to include all the files in the current directory (and any subdirectories) in the newly created jar.
    Although software vendors typically ship their jar with the .class files but not the .java files, your instructor does want to see your source code. (We are doing open source development.)
  • Note that at https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html the syntax is different, so try this syntax if the other syntax does not work:
    jar cfm MyJar.jar Manifest.txt *

How to test a .jar file

To run a jar file

java -jar surgeonInAJar.jar

To see a listing of the files in a jar

jar tf surgeonInAJar.jar

where "t" means show the table of contents, and "f" means you are indicating the file name of the jar

To extract ("inflate") the contents of a jar

jar -xvf surgeonInAJar.jar

  • xvf means extract ("x") in verbose ("v") mode to help debug problems, by specifying the file ("f") on the command line

Tips:

  1. Email the executable jar to yourself and test.
  2. Email the executable .jar file to the instructor as an attachment, with the quiz questions in the body of the email. Do NOT email a .zip file or multiple attachments.

Access Control with the keyword protected

To see an example, download and extract the jar file named protected.jar.




  • No labels
Write a comment…