Category Archives: Lesson

Chapter 3: Multiple Relational Operators

Consider the expression
if (0 < amount < 1000) . . . // Error
This looks just like the mathematical notation for “amount is between 0 and 1000”. But in Java, it is a syntax error.
Let us dissect the condition. The first half, 0 < amount, is a test with outcome true or false. The outcome of that test (true or false) is then compared against 1000. This seems to make no sense. Is true larger than 1000 or not? Can one compare truth values and numbers? In Java, you cannot. The Java compiler rejects this statement.
Instead, use && to combine two separate tests: if (0 < amount && amount < 1000) . . .

Another common error, along the same lines, is to write if (ch == ‘S’ || ‘M’) . . . // Error
to test whether ch is ‘S’ or ‘M’. Again, the Java compiler flags this construct as an error. You cannot apply the || operator to characters. You need to write two Boolean expressions and join them with the || operator:
if (ch == ‘S’ || ch == ‘M’) . . .

Chapter 3: Conditions with Side Effects

In Java, it is legal to nest assignments inside test conditions:
if ((d = b * b – 4 * a * c) >= 0) r = Math.sqrt(d);
It is legal to use the decrement operator inside other expressions:
if (n–– > 0) . . .
These are bad programming practices because they mix a test with another activity. The other activity (setting the variable d, decrementing n) is called a side effect of the test.
Conditions with side effects can occasionally be helpful to simplify loops; for if statements they should always be avoided.

Occasionally all the work of a loop is already done in the loop header. Suppose you ignore good programming practices and write an investment doubling loop as follows:
for (years = 1;
(balance = balance + balance * rate / 100) < targetBalance; years++);
System.out.println(years);
The body of the for loop is completely empty, containing just one empty statement terminated by a semicolon.
If you do run into a loop without a body, it is important that you make sure the semicolon is not forgotten. If the semicolon is accidentally omitted, then the next line becomes part of the loop statement!
for (years = 1;
(balance = balance + balance * rate / 100) < targetBalance; years++)
System.out.println(years);
You can avoid this error by using an empty block { } instead of an empty statement.

Chapter 3: Confusing && and || Conditions

Confusing && and || Conditions
It is a surprisingly common error to confuse “and” and “or” conditions. A value lies between 0 and 100 if it is at least 0 and at most 100. It lies outside that range if it is less than 0 or greater than 100. There is no golden rule; you just have to think carefully.
Often the “and” or “or” is clearly stated, and then it isn’t too hard to implement it. Sometimes, though, the wording isn’t as explicit. It is quite common that the individual conditions are nicely set apart in a bulleted list, but with little indication of how they should be combined. The instructions for the 1992 tax return say that you can claim single filing status if any one of the following is true:
• You were never married.
• You were legally separated or divorced on December 31, 1992.
• You were widowed before January 1, 1992, and did not remarry in 1992.
Because the test passes if any one of the conditions is true, you must combine the conditions with or. Elsewhere, the same instructions state that you may use the more advantageous status of married filing jointly if all five of the following conditions are true:
• Your spouse died in 1990 or 1991 and you did not remarry in 1992.
• You have a child whom you can claim as dependent.
• That child lived in your home for all of 1992.
• You paid over half the cost of keeping up your home for this child.
• You filed (or could have filed) a joint return with your spouse the year he or she died.
Because all of the conditions must be true for the test to pass, you must combine them with an and.

Chapter 5: Software Development Activities

October 11th, 2013

Software Development Activities

Four basic development activities:

  • establishing the requirements
  • creating a design
  • implementing the design
  • testing

This sequence would be ideal but it almost never completely linear in reality.
They overlap and interact.

Software requirements specify what a program must accomplish: a document called a functional specification.

The client will often provide an initial set of requirements. However, these initial requirements are often incomplete, ambiguous, and perhaps even contradictory.

The software developer must work with the client to refine the requirements.

A software design indicates how a program will accomplish its requirements.

The design specifies the classes and objects needed in a program and defines how they interact. It also specifies the relationships among the classes.

During software design, alternatives need to be considered and explored. Often, the first attempt at a design is not the best solution.

Implementation is the process of writing the source code that will
 solve the problem.

Too many programmers focus on implementation exclusively when actually it should be the least creative of all development activities. The important decisions should be made when establishing the requirements and creating the design.

Testing is the act of ensuring that a program will solve the intended problem given all of the constraints under which it must perform.

Identifying classes and objects

A fundamental part of object-oriented software design is determining the classes that will contribute to the program. We have to carefully consider how we want to represent the various elements that make up the overall solution. These classes determine the objects that we will manage in the system.

When designing classes, objects are generally nouns.

The nouns in a problem description may indicate some of the classes and objects needed in a program.

A class represents a group of objects with similar behavior. A plural noun is an indication that your design might not be good.

Classes that represent objects should generally be given names that are singular nouns.

A class represents a single item from which we are free to create as many instances as we choose.

Another key decision is whether to represent something as an object or as a primitive attribute of another object.

We want to strike a good balance between classes that are too general and those that are too specific.

There might be additional classes to support the work necessary to get the job done.

Keep in mind that may be an old class that’s similar enough to serve as the basis for our new class.

The existing class may be part of the Java standard class library, part of a solution to a problem we’ve solved previously, or part of a library that can be bought from a third party, “Software Re-usability”.

Assigning responsibilities

Part of the process of identifying the classes needed in a program is the process of assigning responsibilities to each class. Each class represents an object with certain behaviors that are defined by the methods of the class. Any activity that the program must accomplish must be represented somewhere in the behaviors of the classes. That is, each class is responsible for carrying out certain activities, and those responsibilities must be assigned as part of designing a program.

Generally use verbs for the names of behaviors and the methods that accomplish them.

Sometimes it is challenging to determine which is the best class to carry out a particular responsibility. You could benefit from defining another class to shoulder the responsibility.

It’s not necessary in the early stages of a design to identify all the methods that a class will contain. It is often sufficient to assign primary responsibilities and consider how those responsibilities translate to particular methods.

Class and object relationships

The classes in a software system have various types of relationships to each other. Three of the more common relationships are dependency, aggregation, and inheritance.

Dependency relationships: a class “uses” another.
Class A uses class B, then one or more methods of class A invoke one or more methods of class B. If an invoked method is static, then A merely references B by name. If the invoked method is not static, then A must have access to a specific instance of class B in order to invoke the method. That is, A must have a reference to an object of class B.

dependency

UML notation distinguishes between object diagrams and class diagrams. In an object diagram the class names are underlined; in a class diagram the class names are not underlined. In a class diagram, you denote dependency by a dashed line with a shaped open arrow tip that points to the dependent class. Figure 1 shows a class diagram indicating that the CashRegister class depends on the Coin class.

Note that the Coin class does not depend on the CashRegister class. Coins have no idea that they are being collected in cash registers, and they can carry out their work without ever calling any method in the CashRegister class.

coupling

Aggregation: the objects of one class contain objects of another, creating a “has-a” relationship.
When one class instantiates the objects of another, it is the basis of an aggregation relationship. The access can also be accomplished by passing one object to another as a method parameter.
The less dependent our classes are on each other, the less impact changes and errors will have on the system.

Inheritance: creates an “is-a” relationship between classes.

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: Measurable Interface

DataSet

/**
   Computes the average of a set of data values.
*/
public class DataSet
{
   /**
      Constructs an empty data set.
   */
   public DataSet()
   {
      sum = 0;
      count = 0;
      maximum = 0;
   }

   /**
      Adds a data value to the data set
      @param x a data value
   */
   public void add(double x)
   {
      sum = sum + x;
      if (count == 0 || maximum < x) maximum = x;
      count++;
   }

   /**
      Gets the average of the added data.
      @return the average or 0 if no data has been added
   */
   public double getAverage()
   {
      if (count == 0) return 0;
      else return sum / count;
   }

   /**
      Gets the largest of the added data.
      @return the maximum or 0 if no data has been added
   */
   public double getMaximum()
   {
      return maximum;
   }

   private double sum;
   private double maximum;
   private int count;
}

[collapse]
BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
    
   private double balance;
   private String name;
   

   /**
      Constructs a bank account with a zero balance
   */
   public BankAccount()
   {   
      balance = 0;
      name = "    ";
   }

   /**
      Constructs a bank account with a given balance
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance, String aName)
   {   
      balance = initialBalance;
      name = aName;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      double newBalance = balance + amount;
      balance = newBalance;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      double newBalance = balance - amount;
      balance = newBalance;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }

}

[collapse]
Coin

/**
   A coin with a monetary value.
*/
public class Coin
{
   /**
      Constructs a coin.
      @param aValue the monetary value of the coin.
      @param aName the name of the coin
   */
   public Coin(double aValue, String aName) 
   { 
      value = aValue; 
      name = aName;
   }

   /**
      Gets the coin value.
      @return the value
   */
   public double getValue() 
   {
      return value;
   }

   /**
      Gets the coin name.
      @return the name
   */
   public String getName() 
   {
      return name;
   }

   private double value;
   private String name;
}

[collapse]
BankDataSet

/**
   Computes the average of a set of data values.
*/
public class BankDataSet
{
   /**
      Constructs an empty data set.
   */
   public BankDataSet()
   {
      sum = 0;
      count = 0;
      maximum = null;
   }

   /**
      Adds a bank account balance to the data set
      @param x a data value
   */
   public void add(BankAccount bkAcc)
   {
      sum = sum + bkAcc.getBalance();
      if (count == 0 || maximum.getBalance() < bkAcc.getBalance()) maximum = bkAcc;
      count++;
   }

   /**
      Gets the average of the added data.
      @return the average or 0 if no data has been added
   */
   public double getAverage()
   {
      if (count == 0) return 0;
      else return sum / count;
   }

   /**
      Gets the largest of the added data.
      @return the maximum or 0 if no data has been added
   */
   public BankAccount getMaximum()
   {
      return maximum;
   }

   private double sum;
   private BankAccount maximum;
   private int count;
}

[collapse]
CoinDataSet
/**
   Computes the average of a set of data values.
*/
public class CoinDataSet
{
   /**
      Constructs an empty data set.
   */
   public CoinDataSet()
   {
      sum = 0;
      count = 0;
      maximum = null;
   }

   /**
      Adds a bank account balance to the data set
      @param x a data value
   */
   public void add(Coin aCoin)
   {
      sum = sum + aCoin.getValue();
      if (count == 0 || maximum.getValue() < aCoin.getValue()) maximum = aCoin;
      count++;
   }

   /**
      Gets the average of the added data.
      @return the average or 0 if no data has been added
   */
   public double getAverage()
   {
      if (count == 0) return 0;
      else return sum / count;
   }

   /**
      Gets the largest of the added data.
      @return the maximum or 0 if no data has been added
   */
   public Coin getMaximum()
   {
      return maximum;
   }

   private double sum;
   private Coin maximum;
   private int count;
}

[collapse]

Measurable

/**
 * Interface Measurable: use the implements keyword to indicate that a class 
 * implements an interface type. Unlike a class, an interface type provides no implementation
 * @GE
 * @12/15/17
 */

/**
   Describes any class whose objects can be measured.
*/
public interface Measurable
{
   /**
      Computes the measure of the object.
      @return the measure
   */
   double getMeasure();
}


[collapse]

BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount implements Measurable
{  
   /**
      Constructs a bank account with a zero balance
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      double newBalance = balance + amount;
      balance = newBalance;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      double newBalance = balance - amount;
      balance = newBalance;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }

   public double getMeasure()
   {
      return balance;
   }

   private double balance;
}

[collapse]

Coin
/**
   A coin with a monetary value.
*/
public class Coin implements Measurable
{
   /**
      Constructs a coin.
      @param aValue the monetary value of the coin.
      @param aName the name of the coin
   */
   public Coin(double aValue, String aName) 
   { 
      value = aValue; 
      name = aName;
   }

   /**
      Gets the coin value.
      @return the value
   */
   public double getValue() 
   {
      return value;
   }

   /**
      Gets the coin name.
      @return the name
   */
   public String getName() 
   {
      return name;
   }

   public double getMeasure() 
   {
      return value;
   }

   private double value;
   private String name;
}

[collapse]

DataSet

/**
   Computes the average of a set of data values.
*/
public class DataSet
{
   /**
      Constructs an empty data set.
   */
   public DataSet()
   {
      sum = 0;
      count = 0;
      maximum = null;
   }

   /**
      Adds a data value to the data set
      @param x a data value
   */
   public void add(Measurable x)
   {
      sum = sum + x.getMeasure();
      if (count == 0 || maximum.getMeasure() < x.getMeasure())
         maximum = x;
      count++;
   }

   /**
      Gets the average of the added data.
      @return the average or 0 if no data has been added
   */
   public double getAverage()
   {
      if (count == 0) return 0;
      else return sum / count;
   }

   /**
      Gets the largest of the added data.
      @return the maximum or 0 if no data has been added
   */
   public Measurable getMaximum()
   {
      return maximum;
   }

   private double sum;
   private Measurable maximum;
   private int count;
}

[collapse]

DataSetTest

/**
   This program tests the DataSet class.
*/
public class DataSetTest
{
   public static void main(String[] args)
   {
      DataSet bankData = new DataSet();
      
      bankData.add(new BankAccount(3000));
      bankData.add(new BankAccount(10000));
      bankData.add(new BankAccount(2000));

      System.out.println("Average balance = " 
         + bankData.getAverage());
      
      Measurable max = bankData.getMaximum();
      System.out.println("Highest balance = " 
         + max.getMeasure());
      //System.out.println("Get bank balance = " 
      //   + max.getBalance());
      BankAccount maxAccount = (BankAccount) max;
      System.out.println("Get bank balance = " 
         + maxAccount.getBalance());

      DataSet coinData = new DataSet();

      coinData.add(new Coin(0.25, "quarter"));
      coinData.add(new Coin(0.1, "dime"));
      coinData.add(new Coin(0.05, "nickel"));

      System.out.println("Average coin value = " 
         + coinData.getAverage());
     
      max = coinData.getMaximum();
      System.out.println("Highest coin value = " 
         + max.getMeasure());
     
   }
}

[collapse]

Classwork: Create a class Student that realizes the Measurable interface. Add to the driver, DataSetTest a data set of students. Print the average, the max value and the name of the student.
Submit to “Measurable – Interfaces Lesson Practice” post the following files (you can attach them): BankAccount, Coin, Student, DataSet and DataSetTest. Make sure the output is included in the test class as comment.

//********************************************************************
//  Student.java       Author: Lewis/Loftus/Cocking
//
//  Represents a college student.
//********************************************************************

public class Student
{
   private String firstName, lastName;
   private double GPA; // for Measurable Interface purpose

   //-----------------------------------------------------------------
   //  Sets up this Student object with the specified initial values.
   //-----------------------------------------------------------------
   public Student (String first, String last, double aGPA)
   {
      firstName = first;
      lastName = last;
      GPA = aGPA;
   }

   public String getName()
   {
      return firstName + " " + lastName + "\n";
   }
   //-----------------------------------------------------------------
   //  Returns this Student object as a string.
   //-----------------------------------------------------------------
   public String toString()
   {
      String result;

      result = firstName + " " + lastName + "\n";
      result += GPA

      return result;
   }
}




Assignments:
Programming Projects 5.3 and 5.4

Chapter 5 – Software Life Cycle

Software Development Activities

Four basic development activities:

  • establishing the requirements
  • creating a design
  • implementing the design
  • testing

This sequence would be ideal but it almost never completely linear in reality.
They overlap and interact.

Software requirements specify what a program must accomplish: a document called a functional specification.

The client will often provide an initial set of requirements. However, these initial requirements are often incomplete, ambiguous, and perhaps even contradictory.

The software developer must work with the client to refine the requirements.

A software design indicates how a program will accomplish its requirements.

The design specifies the classes and objects needed in a program and defines how they interact. It also specifies the relationships among the classes.

During software design, alternatives need to be considered and explored. Often, the first attempt at a design is not the best solution.

Implementation is the process of writing the source code that will
 solve the problem.

Too many programmers focus on implementation exclusively when actually it should be the least creative of all development activities. The important decisions should be made when establishing the requirements and creating the design.

Testing is the act of ensuring that a program will solve the intended problem given all of the constraints under which it must perform.

Identifying classes and objects

A fundamental part of object-oriented software design is determining the classes that will contribute to the program. We have to carefully consider how we want to represent the various elements that make up the overall solution. These classes determine the objects that we will manage in the system.

When designing classes, objects are generally nouns.

The nouns in a problem description may indicate some of the classes and objects needed in a program.

A class represents a group of objects with similar behavior. A plural noun is an indication that your design might not be good.

Classes that represent objects should generally be given names that are singular nouns.

A class represents a single item from which we are free to create as many instances as we choose.

Another key decision is whether to represent something as an object or as a primitive attribute of another object.

We want to strike a good balance between classes that are too general and those that are too specific.

There might be additional classes to support the work necessary to get the job done.

Keep in mind that may be an old class that’s similar enough to serve as the basis for our new class.

The existing class may be part of the Java standard class library, part of a solution to a problem we’ve solved previously, or part of a library that can be bought from a third party, “Software Re-usability”.

Assigning responsibilities

Part of the process of identifying the classes needed in a program is the process of assigning responsibilities to each class. Each class represents an object with certain behaviors that are defined by the methods of the class. Any activity that the program must accomplish must be represented somewhere in the behaviors of the classes. That is, each class is responsible for carrying out certain activities, and those responsibilities must be assigned as part of designing a program.

Generally use verbs for the names of behaviors and the methods that accomplish them.

Sometimes it is challenging to determine which is the best class to carry out a particular responsibility. You could benefit from defining another class to shoulder the responsibility.

It’s not necessary in the early stages of a design to identify all the methods that a class will contain. It is often sufficient to assign primary responsibilities and consider how those responsibilities translate to particular methods.

Class and object relationships

The classes in a software system have various types of relationships to each other. Three of the more common relationships are dependency, aggregation, and inheritance.

Dependency relationships: a class “uses” another.
Class A uses class B, then one or more methods of class A invoke one or more methods of class B. If an invoked method is static, then A merely references B by name. If the invoked method is not static, then A must have access to a specific instance of class B in order to invoke the method. That is, A must have a reference to an object of class B.

dependency

UML notation distinguishes between object diagrams and class diagrams. In an object diagram the class names are underlined; in a class diagram the class names are not underlined. In a class diagram, you denote dependency by a dashed line with a shaped open arrow tip that points to the class that is dependent on. Figure 1 shows a class diagram indicating that the CashRegister class depends on the Coin class.

Note that the Coin class does not depend on the CashRegister class. Coins have no idea that they are being collected in cash registers, and they can carry out their work without ever calling any method in the CashRegister class.

coupling

Aggregation: the objects of one class contain objects of another, creating a “has-a” relationship.
When one class instantiates the objects of another, it is the basis of an aggregation relationship. The access can also be accomplished by passing one object to another as a method parameter.
The less dependent our classes are on each other, the less impact changes and errors will have on the system.

Inheritance: creates an “is-a” relationship between classes.

Assignment:

Design an application:

A computer-based system is to be implemented for an airport snack bar business, Goodies Co.
1. Define what the needs are.
2. Based on the previous, create a list of questions for your “client”.
3. Work with your partner to outline the different components to run the company.

vendingmachines

 

Chapter 4: More Concepts

constructors

We don’t have to define a constructor for every class. Each class has a default constructor that takes no parameters and is used if we don’t provide our own. This default constructor generally has no effect on the newly created object.

Local variables

The scope of a variable (or constant) is the part of a program in which a valid reference to that variable can be made. A variable can be declared inside a method, making it local data as opposed to instance data.

A method’s name along with the number, type, and order of its parameters is called the method’s signature. The compiler uses the complete method signature to bind a method invocation to the appropriate definition.

Note that the return type of a method is not part of the method signature.


They are not intended to provide services directly to clients outside the class. Instead, they exist to help the translate method, which is the only true service method in this class, to do its job. By declaring them with private visibility, they can- not be invoked from outside this class.
A predicate method returns a boolean value:

public boolean isOverdrawn()
{
-->return balance < 0;
}

Used in conditions like

if (harrysChecking.isOverdrawn())

Useful predicate methods in Character class:

isDigit()
isLetter()
isUpperCase()
isLowerCase() 

Classwork:
1. At compilation time an ADT’s constructor gives an error. What do you think might be wrong with it?
2. What is the difference between the variables “balance” and “initial” in this constructor?

 public Account (String owner, int account, double initial)
   {
      name = owner;
      acctNumber = account;
      balance = initial;
   }
  1. What is a method’s signature?
  2. Why would you implement a private method?
  3. Write a private predicate method for this code
         
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));

Chapter 4: Objects Revisited

Chapter 4 – Writing Classes

Concepts to discuss:
keyconcept2

  • attributes, states and instance fields
  • behavior and methods

attributesAndMethods1

methodofaclass4

rollingdiceUML5

keyconcept4

  • object variable and object reference
  • classes as blueprints
  • members of a class

memberofaclass3

 

  • constructors

keyconcept11

 

  • methods

flowofcontrol9

methoddeclaration8

keyconcept8

returnmethod10

keyconcept9

passingpara11

  • access specifiers or visibility modifiers

effectofpublicprivatevisibility7

  • What does a predicate method do? It evaluates the predicate on the value passed to this function as the argument and then returns a boolean value.

keyconcept6

 

  • variable scope

keyconcept3

keyconcept10

 

  • ENCAPSULATION

keyconcept5

 

aclientinteraction6

keyconcept7

Answer the following questions:
Lesson Questions

  1. What is an attribute?
  2. What is an operation?
  3. List some attributes and operations that might be defined for a class called Book that represents a book in a library.
  4. True or False? Explain.
    a. We should use only classes from the Java standard class library when writing our programs—there is no need to define or use other classes.
    b. An operation on an object can change the state of an object.
    c. The current state of an object can affect the result of an operation on that object.
    d. In Java, the state of an object is represented by its methods.
  5. What is the difference between an object and a class?
  6. What is the scope of a variable?
  7. What are UML diagrams designed to do?
  8. Objects should be self-governing. Explain.
  9. What is a modifier?
  10. Describe each of the following:
    ◗ public method
    ◗ private method
    ◗ public variable
    ◗ private variable
  11. What does the return statement do?
  12. Explain the difference between an actual parameter and a formal parameter.
  13. What are constructors used for? How are they defined?
  14. How are overloaded methods distinguished from each other?
  15. What is method decomposition?
  16. Explain how a class can have an association with itself.
  17. What is an aggregate object?

Submit your answers as we discuss them. This assignment will take more than one lesson but submit what you have every time we have the lesson.