Category Archives: Homework

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.

 

 

Chapter 5: Interface Lockable – Comparable

January 3rd, 2018

Classwork:

lock

Programming Project 5.6:
Design a Java interface called Lockable that includes the following methods: setKey, lock, unlock, and locked. The setKey, lock, and unlock methods take an integer parameter that represents the key. The setKey method establishes the key. The lock and unlock methods lock and unlock the object, but only if the key passed in is correct. The locked method returns a boolean that indicates whether or not the object is locked. A Lockable object represents an object whose regular methods are protected: if the object is locked, the methods cannot be invoked; if it is unlocked, they can be invoked. Redesign and implement a version of the Coin class from Chapter 4 so that it is Lockable.
Include a driver.

Homework:
Programming Project 5.7:
Redesign and implement a version of the Account class from Chapter 4 so that it is Lockable as defined by Programming Project 5.6.
Include a driver.

Chapter 5: Inner Classes – Nested Classes

January 12th, 2017

Classwork:

Inner Classes – Nested Classes
A class can be declared inside another class. Just as a loop written inside another loop is called a nested loop, a class written inside another class is called a nested class. The nested class is considered a member of the enclosing class, just like a variable or method.

  • Just like any other class, a nested class produces a separate bytecode file.
  • The name of the bytecode file is the name of the enclosing class followed by the $ character followed by the name of the nested class.
  • Like any other bytecode file, it has an extension of .class. A class called Nested that is declared inside a class called Enclosing will result in a compiled bytecode file called Enclosing$Nested.class.
  • Because it is a member of the enclosing class, a nested class has access to the enclosing class’s instance variables and methods, even if they are declared with private visibility.
  • The enclosing class can directly access data in the nested class only if the data is declared public.
  • Data should always be kept private to follow the rules of encapsulation. However, the exception applies to nested class so the enclosing class can get to the data.
  • Such a privileged relationship should be reserved for appropriate situations.
  • The static modifier can be applied to a class, but only if the class is nested inside another.
  • Like static methods, a static nested class cannot reference instance variables or methods defined in its enclosing class.
  • //********************************************************************
    //  TestInner.java       Author: Lewis/Loftus
    //
    //  Demonstrates the access capabilities of inner classes.
    //********************************************************************
       public class TestInner
       {
          //-----------------------------------------------------------------
          //  Creates and manipulates an Outer object.
          //-----------------------------------------------------------------
          public static void main (String[] args)
          {
             Outer out = new Outer();
             System.out.println (out);
             System.out.println();
             out.changeMessages();
             System.out.println (out);
          } 
       }
    

    Output
    Copy these files to your project.
    Show and explain the output on edmodo.com

    
    //********************************************************************
    //  Outer.java       Author: Lewis/Loftus
    //
    //  Represents a class that encapsulates an inner class.
    //********************************************************************
    public class Outer
    {
       private int num;
       private Inner in1, in2;
       //-----------------------------------------------------------------
       //  Sets up this object, initializing one int and two objects
       //  created from the inner class.
       //-----------------------------------------------------------------
       public Outer()
       {
         num = 9876;
         in1 = new Inner ("Half of the problem is 90% mental.");
         in2 = new Inner ("Another deadline. Another miracle.");
       }
       //-----------------------------------------------------------------
       //  Changes the messages in the Inner objects (directly).
       //-----------------------------------------------------------------
       public void changeMessages()
       {
          in1.message = "Life is uncertain. Eat dessert first.";
          in2.message = "One seventh of your life is spent on Mondays.";
       }
       //*****************************************************************
       //  Returns this object                
       //*****************************************************************
    
       public String toString()
       {
          return in1 + "\n" + in2;
       }
    
          //*****************************************************************
          //  Represents an inner class.
          //*****************************************************************
          private class Inner
          {
             public String message;
             //--------------------------------------------------------------
             //  Sets up this Inner object with the specified string.
             //--------------------------------------------------------------
             public Inner (String str)
             {
                message = str;
             }
             //--------------------------------------------------------------
             //  Returns this object as a string, including a value from
             //  the outer class.
             //--------------------------------------------------------------
             public String toString()
             {
                num++;
                return message + "\nOuter num = " + num;
             }
           }
       }
        
    
  • Each Inner object contains a public String called message.
  • Because it is public, the changeMessages of the Outer class can reach in and modify the contents.
  • As the authors’ve stressed many times, giving data public access should be avoided in general. However, in this case, since Inner is a private class, no class other than Outer can refer to it. Therefore no class other than Outer can directly access the public data inside it either.
    Using inner classes with public data should be done only in situations in which the outer class is completely dependent on the inner class for its existence.

    If designed properly, inner classes preserve encapsulation while simplifying the implementation of related classes

    Preparing for chapter 5 test on Wednesday and getting ready for Midterm.

    Homework:
    Study for chapter 5 test.

    Chapter 5: Goodies Co. Examples

    The Goodies Company Project

    vendingmachines

    From Wikipedia:
    In computer programming, an application programming interface (API) is a set of routines, protocols, and tools for building software applications. An API expresses a software component in terms of its operations, inputs, outputs, and underlying types. An API defines functionalities that are independent of their respective implementations, which allows definitions and implementations to vary without compromising the interface. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.

    Cay Horstmann:
    A class should represent a single concept. The public methods
    and constants that the public interface exposes should be cohesive.
    That is, all interface features should be closely related to the single
    concept that the class represents.
    If you find that the public interface of a class refers to multiple concepts,
    then that is a good sign that it may be time to use separate classes instead.

    NO CODE – It is no programming language related!

    Examples of public interfaces for the Goodies Company Application:
    Example 1:

    Class BD_VendingMachine:
    public BD_VendingMachine: initializes allocated change and sets profit to 0
    void addChange(value) adds allocated change
    void addProduct(BD_Product) adds a product to the machine
    double getBalance() returns profit
    double getChange() returns allocated change remaining
    void purchase(BD_Product, double money) buys product inputted and determines change to return, subtracting from allocated change accordingly

    Class BD_Product:
    public BD_Product(string name, double price)initializes new product and price

    Example 2:
    Classes:

    Class 1 – snack
    name, price, stock
    can set the name price and amount of the item
    can change the price of the item
    will decrement the amount when the item is purchased

    Class 2 – machine
    sales, list of snacks
    holds several objects of the class snack
    method for purchasing an item which will decrement the snack, increase sales, and output change
    method for restocking the amount of a snack
    can remove and add snacks
    can return the total sales of a machine

    Class 3/ Main Class –
    runs several of the machines
    will buy snacks from various machines
    will restock the machines
    will check the total sales and amount of snacks in each machine

    Example 3:
    Vending Machine Project Outline

    VendingMachine —> Class
    – Array of Products
    – Amount initially put in for change
    – Total
    – Name / Location
    addProduct() – allows you to add a product object to the inventory of the machine
    addChange() – allows you to add change to the machine
    getProfit() – subtracts the added change from the total to display the profit of the machine
    buy() – takes in a Product object, and a money value (possibly in coin objets) and allows you to “buy” the product

    Product —> Class
    – name
    – price
    getPrice()
    getName()
    toString()

    Coin —> Class
    – name
    – value
    getValue()
    getName()
    toString()

    Example 4:
    buyDrink: contains getPrice, giveChange, will give an error message if there are none left
    toString: will show everything in the machine and its prices (and quantities?)
    addChange: adds to the machine’s change supply w/o buying anything
    getQuantity: tells you how many of a drink are in the machine

    contains different types of drinks (Drink class?)
    takes coins form Coin class

    Example 5:
    order(x) – The order method is called whenever the user places an order. It decreases the
    quantity of the specific item by 1 and adds the price to the overall profit. The item the person
    order is given by x, which is an integer that corresponds to the object.
    makeChange(x, y) – The makeChange method is always called right after the order method. It
    takes in the item as it’s first parameter and the amount the user put into the machine as it’s
    second. Then, it returns how much the machine owes the user.
    getProfit() – The getProfit method returns the total profit the machine makes.
    getQuantity() – The getQuantity method returns the total quantity left of each item in the
    machine.

    Example 6:
    Classes:
    endingMachine: This class deals with Product objects and the number of Product objects that exist. This also deals with money taken from the user.
    Product: This contains instance variables for different products with their descriptions and prices.
    Driver: represents the user’s interaction with the vendingMachine

    Methods (VendingMachine):
    sellProduct: This method gives a product to the user by lowering the stock of that product and increases profit but checks if the amount of inserted money is enough for the purchase. And if not it refuses it and uses the giveChange method to return the rest.
    collectMoney: Collects only the amount of money needed by the machine and allows for sellProduct method.
    giveChange: Gives the remaining amount of money that was given but not required to purchase the product.
    restockItems: Resets the amount of goods that exist in the vendingmachine.

    Product Methods:
    getPrice: gives price of product
    getProductName: gives the name of the product chosen

    Chapter 5: Goodies Co. – The requirements

    Design an application Phase 1 – The business model:

    vendingmachines

    The Goodies Co. maintains a kiosk at a busy location with other competing kiosks. This vending front sells snacks and beverages only. Mrs. Goodies has been operating it manually but she wants to have an automated system that would allow her to manage the kiosk more efficiently.

    The client’s requirements at a glance are as follow:
    It should have two interfaces: one for the customer and another for the business operation.

    Sample of a day’s activity:
    Welcome to Goodies Vending Store
    1. Business Operation
    2. Customer
    3. Exit
    What is your choice? 1

    Business Operations
    1. View Inventory
    2. Re-stock
    3. blah blah …
    4. blah blah …
    5. Back to the main menu
    6. Exit Goodies Vending Store
    What is your choice? 5

    Welcome to Goodies Vending Store
    1. Business Operation
    2. Customer
    3. Exit
    What is your choice? 2

    Welcome to Goodies Vending Store
    Here are your choices:
    1. Drinks
    2. Drygoods
    3. Frozen delights
    4. blah blah
    5. Back to the main menu
    6. Done with purchases
    7. Exit Goodies Vending Store
    1 –> drinks menu should come up

    Prompt the buyer for more purchases or to go back to the main menu.

    What is your choice? 5
    Your total is $22.75

    Bye! See you soon.
    It was a pleasure to serve you!

    Customer Interface

    • Available products and price should be displayed numerically as a text menu.
    • The customer should be able to access the product by pressing a key with a number
    • The customer should be prompted for option number.
    • Payment can be assumed to be exact and correct.
    • Handle payment.
    • Update sales record(s).
    • Update kiosk inventory.
    • Back to customer menu.
    • Prompt the user for product number? Exit?
    • If exit, it should go back to the START of operiations.

    Business Operations

    • The Business Operations should only be accessed by password (Optional)
    • The system should know the quantity, cost, and selling price for each product.
    • It should keep a current inventory of the products in the kiosk and in stock.
    • It should have re-stocking(s) notification(Optional)
    • It should have an option to re-stock both the store and the stockpile
    • Update stockpile inventory
    • It should access information of the net profits based on the sales on demand.

    The START of Operations

    • Welcome message.
    • Load data base of products and prices.
    • Menu: Customer? Business Operations?
    • Chose?/Exit?

    The END of Operations

    • Update database with current quantities.
    • Prompt the business manager for stockpile re-stocking
    • Close database files
    • Goodbye message

    Assumptions

    • Payment is exact and correct.
    • Products pricess never change

    Chapter 5: References Revisited

    References revisited:

    – An object reference variable and an object are two different things.
    – The declaration of the reference variable and the creation of the object that it refers to are separate steps.
    – The dot operator uses the address in the reference variable.
    – A reference variable that doesn’t point to an object is called a null reference.
    – When a reference variable is first declared as an instance variable, it is a null reference.
    – Accessing a null reference will cause a NullPointerException.

    What is the problem with this class?

    1. public class ACommonMistake
    2.{
    3.  public ACommonMistake()
    4.  {
    5.    System.out.println(lastName.length());
    6.  }
    
    7.  public void aMethod()
    8.   {
    9.    String firstName;
    10.   System.out.println(firstName.length());
    11.  }
    
    12. private String lastName;
    13.}

    The this reference:
    – The “this” word is a reserved word in Java.
    – It lets an object refer to itself.
    – A method is always invoked through (or by) a particular object or class.
    – Inside the method, the “this” reference can be used to refer the currently executing object.

    Aliases:
    An object reference variable stores an address therefore an assignment like this:

    ChessPiece bishop1 = new ChessPiece();
    ChessPiece bishop2 = bishop1;
    Will make the two object variables refer to the same object.

    Method Parameters Revisited:

    In Java, all parameters are passed by value. That is, the current value of the actual parameter (in the invocation) is copied into the formal parameter in the method header.

    //********************************************************************
    //  ParameterTester.java       Author: Lewis/Loftus
    //
    //  Demonstrates the effects of passing various types of parameters.
    //********************************************************************
    
    public class ParameterTester
    {
       //-----------------------------------------------------------------
       //  Sets up three variables (one primitive and two objects) to
       //  serve as actual parameters to the changeValues method. Prints
       //  their values before and after calling the method.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          ParameterModifier modifier = new ParameterModifier();
    
          int a1 = 111;
          Num a2 = new Num (222);
          Num a3 = new Num (333);
    
          System.out.println ("Before calling changeValues:");
          System.out.println ("a1\ta2\ta3");                       
          System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n");   // 1st print
    
          modifier.changeValues (a1, a2, a3);
    
          System.out.println ("After calling changeValues:");
          System.out.println ("a1\ta2\ta3");
          System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n");  // 4th print
       }
    }
    
    //********************************************************************
    //  ParameterModifier.java       Author: Lewis/Loftus
    //
    //  Demonstrates the effects of changing parameter values.
    //********************************************************************
    
    public class ParameterModifier
    {
       //-----------------------------------------------------------------
       //  Modifies the parameters, printing their values before and
       //  after making the changes.
       //-----------------------------------------------------------------
       public void changeValues (int f1, Num f2, Num f3)
       {
          System.out.println ("Before changing the values:");
          System.out.println ("f1\tf2\tf3");
          System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n");  // 2nd print
    
          f1 = 999;
          f2.setValue(888);
          f3 = new Num (777);
    
          System.out.println ("After changing the values:");
          System.out.println ("f1\tf2\tf3");
          System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n");  // 3rd print
       }
    }
    
    
    //********************************************************************
    //  Num.java       Author: Lewis/Loftus
    //
    //  Represents a single integer as an object.
    //********************************************************************
    
    public class Num
    {
       private int value;
    
       //-----------------------------------------------------------------
       //  Sets up the new Num object, storing an initial value.
       //-----------------------------------------------------------------
       public Num (int update)
       {
          value = update;
       }
    
       //-----------------------------------------------------------------
       //  Sets the stored value to the newly specified value.
       //-----------------------------------------------------------------
       public void setValue (int update)
       {
          value = update;
       }
    
       //-----------------------------------------------------------------
       //  Returns the stored integer value as a string.
       //-----------------------------------------------------------------
       public String toString ()
       {
          return value + "";
       }
    }
    
    

    output1

    output2

    in main

    in memory

    passing parameters

    Classwork:
    1. Why does a3 end up with 333 and not 777?
    2. Why a1 isn’t 999 after execution of ParameterTester?
    3. Does a1 ever change to 999?
    4. Why does a2 change to 888?
    5. When does a2 change to 888?
    6. Why can a2 change to a different value while a1 and a3 can’t?

     

    Chapter 4: Be Rational

    Chapter 4 Programming Assignment 7
    Write an application, RationalOperations_YI.java that lets the user add, subtract, multiply, or divide two fractions. Use the Rational class in your implementation. Implement the driver class to test all operations. Have a loop prompting the user for operators and operands.

    Screen Shot 2014-10-01 at 12.48.04 PM

    //********************************************************************
    //  RationalNumbers.java       Author: Lewis/Loftus/Cocking
    //  BeRational Assignment: change this driver so the user can input Rational
    //  numbers and selects the operations
    //  Prompt the user for the rational RationalNumbers
    //  Prompt the user for the operations
    //  Driver to exercise the use of multiple Rational objects.
    //********************************************************************
    
    public class RationalNumbers
    {
       //-----------------------------------------------------------------
       //  Creates some rational number objects and performs various
       //  operations on them.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {     
          Rational r1 = new Rational (6, 8);
          Rational r2 = new Rational (1, 3);
          Rational r3, r4, r5, r6, r7;
    
          System.out.println ("First rational number: " + r1);
          System.out.println ("Second rational number: " + r2);
    
          if (r1.equals(r2))
             System.out.println ("r1 and r2 are equal.");
          else
             System.out.println ("r1 and r2 are NOT equal.");
    
          r3 = r1.reciprocal();
          System.out.println ("The reciprocal of r1 is: " + r3);
    
          r4 = r1.add(r2);
          r5 = r1.subtract(r2);
          r6 = r1.multiply(r2);
          r7 = r1.divide(r2);
    
          System.out.println ("r1 + r2: " + r4);
          System.out.println ("r1 - r2: " + r5);
          System.out.println ("r1 * r2: " + r6);
          System.out.println ("r1 / r2: " + r7);
       }
    }
    
    

    Chapter 4 Programming Assignment 8
    Modify the Student class (Listing 4.13) with the following changes:

    a. Each student object also contains the scores for three tests.

    b. Provide a constructor that sets all instance values based on parameter values. Overload the constructor so that each test score starts out at zero.

    c. Provide a method called setTestScore that accepts two parameters: the test number (1 through 3) and the score.

    d. Provide a method called getTestScore that accepts the test number and returns the score.

    e. Provide a method called average that computes and returns the average test score for this student.

    f. Modify the toString method so that the test scores and average are included in the description of the student.

    g. Modify the driver class main method to exercise the new Student methods.

    Chapter 4: Lessons Questions Part 3

    Classwork/Homework:
    Answer the following questions:

    1. What does the author mean by “Objects should be self-governing”?

    2. What is the “public interface” to an object?

    3. Why might a constant be given public visibility?

    4. Why is a method invoked through (or on) a particular object? What is the exception to that rule?

    5. In the Banking program:
      a. How many Account objects are created?
      b. How many arguments (actual parameters) are passed to the
      withdraw method when it is invoked on the acct2 object?
      c. How many arguments (actual parameters) are passed to the
      addInterest method when it is invoked on the acct3 object?

    6. Which of the Account class methods would you classify as accessor
      methods? As mutator methods? As service methods?

    Read up to page 225

    Chapter 4: Method decomposition – Static Variables & methods

    From Java Software Solutions by Lewis, Loftus, and Cocking
    Static Keyword youtube Video

    Static Keyword Video

    Assignments:
    1. Explain why a static method cannot refer to an instance variable.
    2. Can a static method be referenced with the “this” operator? Explain
    3. What is the purpose of static variables since a static variable belongs to the class, not to an object?
    4. How are static variables and methods used?
    5. Modify the PigLatinTranslator class so that its translate method is static. Modify the PigLatin class so that it invokes the method correctly.

    Method decomposition

    Sometimes it is useful to decompose a method into multiple methods to create a more understandable design. As an example, let’s examine a program that translates English sentences into Pig Latin.

    Pig Latin is a made-up language in which each word of a sentence
is modified, in general, by moving the initial sound of the word to the end and adding an “ay” sound. For example, the word happy would be written and pronounced appyhay and the word birthday would become irthdaybay. Words that begin with vowels simply have a “yay” sound added on the end, turning the word enough into enoughyay. Consonant blends such as “ch” and “st” at the beginning of a word are moved to the end together before adding the “ay” sound. Therefore the word grapefruit becomes apefruitgray.

    The real workhorse behind the PigLatin program is the PigLatinTranslator class. An object of type PigLatinTranslator provides a method called translate, which accepts a string and translates it into Pig Latin. Note that the PigLatinTranslator class does not contain a constructor because none is needed.

    //********************************************************************
    //  PigLatin.java       Author: Lewis/Loftus
    //
    //  Demonstrates the concept of method decomposition.
    //********************************************************************
    
    import java.util.Scanner;
    
    public class PigLatin
    {
       //-----------------------------------------------------------------
       //  Reads sentences and translates them into Pig Latin. 
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          String sentence, result, another;
          PigLatinTranslator translator = new PigLatinTranslator();
          Scanner scan = new Scanner (System.in);
    
          do
          {
             System.out.println ();
             System.out.println ("Enter a sentence (no punctuation):");
             sentence = scan.nextLine();
    
             System.out.println ();
    
             result = translator.translate (sentence);
             System.out.println ("That sentence in Pig Latin is:");
             System.out.println (result);
    
             System.out.println ();
             System.out.print ("Translate another sentence (y/n)? ");
             another = scan.nextLine();
          }
          while (another.equalsIgnoreCase("y"));
       }
    }
    
    
    

     

    //********************************************************************
    //  PigLatinTranslator.java       Author: Lewis/Loftus
    //
    //  Represents a translator from English to Pig Latin. Demonstrates
    //  method decomposition.
    //********************************************************************
    
    import java.util.Scanner;
    
    public class PigLatinTranslator
    {
       //-----------------------------------------------------------------
       //  Translates a sentence of words into Pig Latin.
       //-----------------------------------------------------------------
       public String translate (String sentence)
       {
          String result = "";
    
          sentence = sentence.toLowerCase();
    
          Scanner scan = new Scanner (sentence);
    
          while (scan.hasNext())
          {
             result += translateWord (scan.next());
             result += " ";
          }
    
          return result;
       }
    
       //-----------------------------------------------------------------
       //  Translates one word into Pig Latin. If the word begins with a
       //  vowel, the suffix "yay" is appended to the word.  Otherwise,
       //  the first letter or two are moved to the end of the word,
       //  and "ay" is appended.
       //-----------------------------------------------------------------
       private String translateWord (String word)
       {
          String result = "";
    
          if (beginsWithVowel(word))
             result = word + "yay";
          else
             if (beginsWithBlend(word))
                result = word.substring(2) + word.substring(0,2) + "ay";
             else
                result = word.substring(1) + word.charAt(0) + "ay";
    
          return result;
       }
    
       //-----------------------------------------------------------------
       //  Determines if the specified word begins with a vowel.
       //-----------------------------------------------------------------
       private boolean beginsWithVowel (String word)
       {
          String vowels = "aeiou";
    
          char letter = word.charAt(0);
    
          return (vowels.indexOf(letter) != -1);
       }
    
       //-----------------------------------------------------------------
       //  Determines if the specified word begins with a particular
       //  two-character consonant blend.
       //-----------------------------------------------------------------
       private boolean beginsWithBlend (String word)
       {
          return ( word.startsWith ("bl") || word.startsWith ("sc") ||
                   word.startsWith ("br") || word.startsWith ("sh") ||
                   word.startsWith ("ch") || word.startsWith ("sk") ||
                   word.startsWith ("cl") || word.startsWith ("sl") ||
                   word.startsWith ("cr") || word.startsWith ("sn") ||
                   word.startsWith ("dr") || word.startsWith ("sm") ||
                   word.startsWith ("dw") || word.startsWith ("sp") ||
                   word.startsWith ("fl") || word.startsWith ("sq") ||
                   word.startsWith ("fr") || word.startsWith ("st") ||
                   word.startsWith ("gl") || word.startsWith ("sw") ||
                   word.startsWith ("gr") || word.startsWith ("th") ||
                   word.startsWith ("kl") || word.startsWith ("tr") ||
                   word.startsWith ("ph") || word.startsWith ("tw") ||
                   word.startsWith ("pl") || word.startsWith ("wh") ||
                   word.startsWith ("pr") || word.startsWith ("wr") ); 
       }
    }
    
    
    

     

    The act of translating an entire sentence into Pig Latin is not trivial. If written in one big method, it would be very long and difficult to follow. A better solution, as implemented in the PigLatinTranslator class, is to decompose the translate method and use several other support methods to help with the task.

    The translate method uses a Scanner object to separate the string into words.

    The Scanner class is to separate a string into smaller elements called tokens. In this case, the tokens are separated by space characters so we can use the default white space delimiters. The PigLatin program assumes that no punctuation is included in the input.

    The methods:

    • translateWord
    • beginsWithVowel
    • beginsWithBlend

    Note that instead of checking each vowel separately, the code for this method declares a string that contains all the vowels, and then invokes the String method indexOf to determine whether the first character of the word is in the vowel string. If the specified character cannot be found, the indexOf method returns a value of 1.

    The UML class diagram for the PigLatin program if drawn below. Note the notation showing the visibility of various methods.

    uml

    Static Variables

    • We’ve used static methods. For example, all the methods of the Math class are static. Recall that a static method is one that is invoked through its class name, instead of through an object of that class.
    • Not only can methods be static, but variables can be static as well. We declare static class members using the static modifier.
    • Deciding whether to declare a method or variable as static is a key step in class design.
    • So far, we’ve seen two categories of variables: local variables that are declared inside a method, and instance variables that are declared in a class but not inside a method. The term instance variable is used, because each instance of the class has its own version of the variable. That is, each object has distinct memory space for each variable so that each object can have a distinct value for that variable.
    • A static variable, which is sometimes called a class variable, is shared among all instances of a class. There is only one copy of a static variable for all objects of the class. Therefore, changing the value of a static variable in one object changes it for all of the others.
    • The reserved word static is used as a modifier to declare a static variable as follows:
                         private static int count = 0;
    • Well you are right public static variables are used without making an instance of the class but private static variables are not. The main difference between them and where I use the private static variables is when you need to use a variable in a static function. For the static functions you can only use static variables, so you make them private to not access them from other classes. That is the only case I use private static for.

      Here is an example:

      Class test {
         public static String name = "AA";
         private static String age;
      
         public static void setAge(String yourAge) {
             //here if the age variable is not static you will get an error that you cannot access non-static variables from static procedures so you have to make it static and private to not be accessed from other classes
             age = yourAge;
         }
      }
      
      

      screen-shot-2016-10-21-at-7-43-43-am

    • Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
    • A local variable declared within a method cannot be static.
    • Constants, which are declared using the final modifier, are often declared using the static modifier. Because the value of constants cannot be changed, there might as well be only one copy of the value across all objects of the class.

    Static Methods

    • A static method is also called a class method. Static methods can be invoked through the class name. We don’t have to instantiate an object of the class in order to invoke the method. We know that all the methods of the Math class are static methods. For example, in the following line of code the sqrt method is invoked through the Math class name:

                          System.out.println (“Square root of 27: ” + Math.sqrt(27));

    • The methods in the Math class perform basic computations based on values passed as parameters. There is no object state to maintain in these situations; therefore, there is no good reason to create an object in order to request these services.
    • A method is made static by using the static modifier in the method declaration.
    • As we’ve seen many times, the main method of a Java program must be declared with the static modifier; this is done so that main can be executed by the interpreter without instantiating an object from the class that contains main.
    • Because static methods do not operate in the context of a particular object, they cannot reference instance variables, which exist only in an instance of a class. The compiler will issue an error if a static method attempts to use a nonstatic variable.
    • A static method can, however, reference static variables, because static variables exist independent of specific objects. Therefore, the main method can access only static or local variables.
    • The program below, SloganCounter instantiates several objects of the Slogan class, printing each one out in turn. At the end of the program it invokes a method called getCount through the class name, which returns the number of Slogan objects that were instantiated in the program.
    //********************************************************************
    //  SloganCounter.java       Author: Lewis/Loftus
    //
    //  Demonstrates the use of the static modifier.
    //********************************************************************
    
    public class SloganCounter
    {
       //-----------------------------------------------------------------
       //  Creates several Slogan objects and prints the number of
       //  objects that were created.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          Slogan obj;
    
          obj = new Slogan ("Remember the Alamo.");
          System.out.println (obj);
    
          obj = new Slogan ("Don't Worry. Be Happy.");
          System.out.println (obj);
    
          obj = new Slogan ("Live Free or Die.");
          System.out.println (obj);
    
          obj = new Slogan ("Talk is Cheap.");
          System.out.println (obj);
    
          obj = new Slogan ("Write Once, Run Anywhere.");
          System.out.println (obj);
    
          System.out.println();
          System.out.println ("Slogans created: " + Slogan.getCount());
       }
    }
    
    
    
    • The next program shows the Slogan class. The constructor of Slogan increments a static variable called count, which is initialized to zero when it is declared. Therefore, count serves to keep track of the number of instances of Slogan that are created.
    • The getCount method of Slogan is also declared as static, which allows it to be invoked through the class name in the main method.
    • Note that the only data referenced in the getCount method is the integer variable count, which is static.
    • As a static method, getCount cannot reference any nonstatic data.
    • The getCount method could have been declared without the static modifier, but then its invocation in the main method would have to have been done through an instance of the Slogan class instead of the class itself.

     

    //********************************************************************
    //  Slogan.java       Author: Lewis/Loftus
    //
    //  Represents a single slogan string.
    //********************************************************************
    
    public class Slogan
    {
       private String phrase;
       private static int count = 0;
    
       //-----------------------------------------------------------------
       //  Constructor: Sets up the slogan and counts the number of
       //  instances created.
       //-----------------------------------------------------------------
       public Slogan (String str)
       {
          phrase = str;
          count++;
       }
    
       //-----------------------------------------------------------------
       //  Returns this slogan as a string.
       //-----------------------------------------------------------------
       public String toString()
       {
          return phrase;
       }
    
       //-----------------------------------------------------------------
       //  Returns the number of instances of this class that have been
       //  created.
       //-----------------------------------------------------------------
       public static int getCount ()
       {
          return count;
       }
    }