Chapter 5: Interfaces – Zero ADT

Exception Handling
An exception is an object created to handle unusual or specific errors.
An exception is thrown by a program or the run-time environment.
An exception can be caught and handled appropriately when needed.
An error is similar to an exception except that an error runs its course.
Java has a predefined set of exceptions and errors that may occur during the execution of a program.

zeromile

//********************************************************************
//  Zero.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates an uncaught exception.
//********************************************************************

public class Zero
{
   //-----------------------------------------------------------------
   //  Deliberately divides by zero to produce an exception.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int numerator = 10;
      int denominator = 0;

      System.out.println (numerator / denominator);

      System.out.println ("This text will not be printed.");
   }
}

Run Zero.java. Does it compile? Does it run?
Answer this question in edmodo.com

/**
 * This class demonstrates the use of exception classes
 * 
 * @Lewis/Loftus/Cocking/Elia
 * @10/21/14
 */
public class ExceptionsExample
{
    
    //********************************************************************
//  Zero.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates an uncaught exception and how to handle it
//********************************************************************

   //-----------------------------------------------------------------
   //  Deliberately divides by zero to produce an exception during runtime.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int numerator = 10;
      int denominator = 0;

      //System.out.println (numerator / denominator);

      //.out.println ("This text will not be printed.");
      
      // handling the exception with try and catch
      
      
      try
         {
            System.out.println (numerator / denominator);
         }
         catch (ArithmeticException e)
         {
            System.out.println ("Improper denominator input validation");
         }
         catch (NumberFormatException exception)
         {
            System.out.println ("Improper number format");
         }
      
   }
}

/**
 * output: Improper denominator input validation
 */



Interfaces

A Java interface is a collection of constants and abstract methods.
An interface cannot be instantiated.
A class implements an interface by providing method implementations for each of the abstract methods defined in the interface.
Methods in interfaces have public visibility by default.

In addition to, or instead of, abstract methods, an interface can also contain constants, defined using the final modifier. When a class implements an inter- face, it gains access to all the constants defined in it.

An interface is represented similarly to a class node except that the designation

 <> 

is inserted above the interface name. A dotted arrow with a closed arrowhead is drawn from the class to the interface that it implements.

Screen Shot 2014-10-21 at 1.53.23 PM

//********************************************************************
//  Complexity.java       Author: Lewis/Loftus/Cocking
//
//  Represents the interface for an object that can be assigned an
//  explicit complexity.
//********************************************************************

public interface Complexity
{
   public void setComplexity (int complexity);
   public int getComplexity();
}

 

//********************************************************************
//  Question.java       Author: Lewis/Loftus/Cocking
//
//  Represents a question (and its answer).
//********************************************************************

public class Question implements Complexity
{
   private String question, answer;
   private int complexityLevel;

   //-----------------------------------------------------------------
   //  Sets up the question with a default complexity.
   //-----------------------------------------------------------------
   public Question (String query, String result)
   {
      question = query;
      answer = result;
      complexityLevel = 1;
   }

   //-----------------------------------------------------------------
   //  Sets the complexity level for this question.
   //-----------------------------------------------------------------
   public void setComplexity (int level)
   {
      complexityLevel = level;
   }

   //-----------------------------------------------------------------
   //  Returns the complexity level for this question.
   //-----------------------------------------------------------------
   public int getComplexity()
   {
      return complexityLevel;
   }

   //-----------------------------------------------------------------
   //  Returns the question.
   //-----------------------------------------------------------------
   public String getQuestion()
   {
      return question;
   }
   //-----------------------------------------------------------------
   //  Returns the answer to this question.
   //-----------------------------------------------------------------
   public String getAnswer()
   {
      return answer;
   }

   //-----------------------------------------------------------------
   //  Returns true if the candidate answer matches the answer.
   //-----------------------------------------------------------------
   public boolean answerCorrect (String candidateAnswer)
   {
      return answer.equals(candidateAnswer);
   }

   //-----------------------------------------------------------------
   //  Returns this question (and its answer) as a string.
   //-----------------------------------------------------------------
   public String toString()
   {
      return question + "\n" + answer;
   }
}

Replace the Keyboard Class with Scanner

//********************************************************************
//  MiniQuiz.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a class that implements an interface.
//********************************************************************



public class MiniQuiz
{
   //-----------------------------------------------------------------
   //  Presents a short quiz.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Question q1, q2;
      String possible;

      q1 = new Question ("What is the capital of Jamaica?",
                         "Kingston");
      q1.setComplexity (4);

      q2 = new Question ("Which is worse, ignorance or apathy?",
                         "I don't know and I don't care");
      q2.setComplexity (10);

      System.out.print (q1.getQuestion());
      System.out.println (" (Level: " + q1.getComplexity() + ")");
      possible = Keyboard.readString();
      if (q1.answerCorrect(possible))
         System.out.println ("Correct");
      else
         System.out.println ("No, the answer is " + q1.getAnswer());

      System.out.println();
      System.out.print (q2.getQuestion());
      System.out.println (" (Level: " + q2.getComplexity() + ")");
      possible = Keyboard.readString();
      if (q2.answerCorrect(possible))
         System.out.println ("Correct");
      else
         System.out.println ("No, the answer is " + q2.getAnswer());
   }
}


 

Classwork:
1. What is the difference between an error and an exception?
2. What is the difference between a class and an interface?
3. Define a Java interface called Nameable. Classes that implement this interface must provide a setName method that requires a single String parameter and returns nothing, and a getName method that has no parameters and returns a String.
4. True or False? Explain.
a. A Java interface can include only abstract methods, nothing else.
b. An abstract method is a method that does not have an implementation.
c. All of the methods included in a Java interface definition must be
abstract.
d. A class that implements an interface can define only those methods
that are included in the interface.
e. Multiple classes can implement the same interface.
f. A class can implement more than one interface.
g. All classes that implement an interface must provide the exact
same definitions of the methods that are included in the interface.

Read up to pages 263 through 269 from Chapter 5.