Category Archives: Lesson

Chapter 7: Inheritance Method behavior

Inheritance
Method behavior

Base and Derived classes are simple classes with one constructor and two methods

Constructors and Methods

Study the code and the output from the driver class. Make conclusions and post them in edmodo.com

Constructor behavior
Basic Inheritance Constructors Behavior

Study the code and the output from the driver class. Make conclusions and post them in edmodo.com

Classwork:
Implement an application similar to the one above to show:

  1. Calls to constructors with and without “super”
  2. Calls to methods with and without “super”
  3. Polymorphism – late binding
  4. Do not forget to keep your code well documented with clear explanations

Assignments:
Self-Review 7.1 through 7.8
Programming Project 7.5

Visit edmodo.com

Chapter 7: Polymorphism in Inheritance and Interfaces: BankAccount


Polymorphism and Inheritance

In Java, the type of a variable does not completely determine the type of the object to which it refers. For example, a variable of type BankAccount can hold a reference to an actual BankAccount object or a subclass object such as SavingsAccount. You already encountered this phenomenon with variables whose type was an interface. A variable whose type is Measurable holds a reference to an object of a class that implements the Measurable interface, perhaps a Coin object or an object of an entirely different class.

What happens when you invoke a method? For example,

BankAccount anAccount = new CheckingAccount();
anAccount.deposit(1000);

Which deposit method is called? The anAccount parameter has type BankAccount, so it would appear as if BankAccount.deposit is called. On the other hand, the CheckingAccount class provides its own deposit method that updates the transaction count. The anAccount field actually refers to an object of the subclass CheckingAccount, so it would be appropriate if the CheckingAccount.deposit method were called instead.

In Java, method calls are always determined by the type of the actual object, not the type of the object reference. That is, if the actual object has the type CheckingAccount, then the CheckingAccount.deposit method is called. It does not matter that the object reference is stored in a field of type BankAccount. The ability to refer to objects of multiple types with varying behavior is called polymorphism .

If polymorphism is so powerful, why not store all account references in variables of type Object? This does not work because the compiler needs to check that only legal methods are invoked. The Object type does not define a deposit method—the BankAccount type (at least) is required to make a call to the deposit method.

Have another look at the transfer method to see polymorphism at work. Here is the implementation of the method:


public void transfer(double amount, BankAccount other)
{
   withdraw(amount);
   other.deposit(amount);
}


Suppose you call

anAccount.transfer(1000, anotherAccount);

Two method calls are the result:

anAccount.withdraw(1000);
anotherAccount.deposit(1000);

Depending on the actual types of anAccount and anotherAccount, different versions of the withdraw and deposit methods are called.

If you look into the implementation of the transfer method, it may not be immediately obvious that the first method call

withdraw(amount);

depends on the type of an object. However, that call is a shortcut for

this.withdraw(amount);

The this parameter holds a reference to the implicit parameter, which can refer to a BankAccount or a subclass object.

The following program calls the polymorphic withdraw and deposit methods.
Manually calculate what the program should print on edmodo.com for each account balance, and confirm that the correct methods have in fact been called.

AccountTester is the driver class:

  /**
     This program tests the BankAccount class and
     its subclasses.
  */
  public class AccountTester
  {
     public static void main(String[] args)
     {
        SavingsAccount momsSavings
             = new SavingsAccount(0.5);

       CheckingAccount harrysChecking
             = new CheckingAccount(100);

       momsSavings.deposit(10000);

       momsSavings.transfer(2000, harrysChecking);
       harrysChecking.withdraw(1500);
       harrysChecking.withdraw(80);

       momsSavings.transfer(1000, harrysChecking);
       harrysChecking.withdraw(400);

       // Simulate end of month
       momsSavings.addInterest();
       harrysChecking.deductFees();

       System.out.println("Mom\'s savings balance: "
             + momsSavings.getBalance());
       System.out.println("Expected: ????");

       System.out.println("Harry\'s checking balance: "
             + harrysChecking.getBalance());
       System.out.println("Expected: ????");
    }
 }

BankAccount Class:

  /**
     A bank account has a balance that can be changed by
     deposits and withdrawals.
  */
  public class BankAccount
  {
     /**
        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)
    {
       balance = balance + amount;
    }

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

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

    /**
       Transfers money from the bank account to another account.
       @param amount the amount to transfer
       @param other the other account
    */
    public void transfer(double amount, BankAccount other)
    {
       withdraw(amount);
       other.deposit(amount);
    }

    private double balance;
 }

CheckingAccount Class derived from BankAccount:

  /**
     A checking account that charges transaction fees.
  */
  public class CheckingAccount extends BankAccount
  {
     /**
        Constructs a checking account with a given balance.
        @param initialBalance the initial balance
     */
    public CheckingAccount(double initialBalance)
    {
       // Construct superclass
       super(initialBalance);

       // Initialize transaction count
       transactionCount = 0;
    }

    public void deposit(double amount)
    {
       transactionCount++;
       // Now add amount to balance
       super.deposit(amount);
    }

    public void withdraw(double amount)
    {
       transactionCount++;
       // Now subtract amount from balance
       super.withdraw(amount);
    }

    /**
       Deducts the accumulated fees and resets the
       transaction count.
    */
    public void deductFees()
    {
       if (transactionCount > FREE_TRANSACTIONS)
       {
          double fees = TRANSACTION_FEE *
                (transactionCount - FREE_TRANSACTIONS);
          super.withdraw(fees);
       }
       transactionCount = 0;
    }

    private int transactionCount;

    private static final int FREE_TRANSACTIONS = 3;
    private static final double TRANSACTION_FEE = 2.0;
 }



SavingsAccount derived from BankAccount:

 /**
   An account that earns interest at a fixed rate.
 */
 public class SavingsAccount extends BankAccount
 {
   /**
      Constructs a bank account with a given interest rate.
      @param rate the interest rate
   */
   public SavingsAccount(double rate)
   {
      interestRate = rate;
   }

   /**
      Adds the earned interest to the account balance.
   */
   public void addInterest()
   {
      double interest = getBalance() * interestRate / 100;
      deposit(interest);
   }

   private double interestRate;
}


Look up the definition of the standard Comparable interface in the API documentation. Modify the DataSet class to accept Comparable objects. With this interface, it is no longer meaningful to compute the average. The DataSet class should record the minimum and maximum data values. Test your modified DataSet class by adding a number of String objects. (The String class implements the Comparable interface.)

Complete the following class in your solution:

DataSet Class takes objects of classes that implement the Comparable interface:

/**
   Computes the minimum and maximum of a set of Comparable values.
*/
public class DataSet
{
   /**
      Constructs an empty data set.
   */
   public DataSet()
   {
      . . .
   }

   /**
      Adds a data value to the data set.
      @param x a data value
   */
   public void add(Comparable x)
   {
      . . .
   }

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

   /**
      Gets the largest of the added data.
      @return the maximum or null if no data has been added
   */
   public Comparable getMinimum()
   {
      . . .
   }

   . . .
}


Use the following class as your tester class:

/**
   This program demonstrates the use of the DataSet that accepts
   instances of the Comparable interface.
*/
public class DataSetTester
{
   public static void main(String[] args)
   {
      DataSet data = new DataSet();
   
      data.add("Helen");
      data.add("Andy");
      data.add("Robert");
      data.add("Vicky");

      Comparable max = data.getMaximum();
      Comparable min = data.getMinimum();
      System.out.println("Maximum: " + max);
      System.out.println("Expected: Vicky");
      System.out.println("Minimum: " + min);
      System.out.println("Expected: Andy");
   }
}

Assignments:
1. From the classes discussed above, draw the UML class diagram and show/demonstrate late binding in inheritance for the BankAccount classes.

  1. Show/demonstrate late binding in inheritance for the StaffCrew classes.
    abstract public class StaffCrew
    Volunteer extends StaffCrew
    FullTimeStaff extends StaffCrew
    Supervisor extends FullTimeStaff
    PartTime extends FullTimeStaff

Chapter 7: Polymorphism and Interfaces Concepts

Classwork: Constructors and Methods behavior diagrams.

Polymorphism and Interfaces:

In Java, all instance methods are polymorphic. The same computation works for objects of many shapes, and adapts itself to the nature of the objects.

Polymorphism denotes the principle that behavior can vary depending on the actual type of an object.

When the virtual machine calls an instance method, it locates the method of the implicit parameter’s class. This is called dynamic method lookup.

Dynamic method lookup enables a programming technique called polymorphism.

There is an important difference between polymorphism and overloading. The compiler picks an overloaded method when translating the program, before the program ever runs. This method selection is called early binding.

Interfaces: when selecting the appropriate getMeasure method in a call x.getMeasure(), the compiler does not make any decision when translating the method as mentioned above. The program has to run before anyone can know what is stored in x. Therefore, the virtual machine, and not the compiler, selects the appropriate method. This method selection is called late binding.

Using a polymorphic reference as the formal parameter to a method is a powerful technique. It allows the method to control the types of parameters passed into it, yet gives it the flexibility to accept arguments of various types.

Looking again at the driver for the DataSet of Measurable objects, we have seen this code:

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()); 
      // ERROR since "max" is not an object of BankAccount
      BankAccount maxAccount = (BankAccount) max; 
      // casting from interfaces to classes
      // max ---> maxAccount ( object of BankAccount )
      System.out.println("Get bank balance = " + maxAccount.getBalance());
      // NO ERROR
      ....
}

To protect against bad casts, you can use the instanceof operator.

Here is a good example:

if ( max instaceof BankAccount )
   {
      BankAccount maxAccount = (BankAccount) max; 
      System.out.println("Get bank balance = " + maxAccount.getBalance());
    }

Homework:
Check edmodo.com

Chapter 7: Inheritance – Method Behavior

Inheritance
Method behavior

Base and Derived classes are simple classes with one constructor and two methods

Parent class

public class Base
{
    public Base()
    {
        System.out.println("Constructor from Base class ");
    }
    public void methodOne()
    {
        System.out.println("methodOne from Base class");
    }
    public void methodTwo()
    {
        System.out.println("methodTwo from Base class");
    }
    
} 

Child class

public class Derived extends Base
{
    public Derived()
    {
        System.out.println("Constructor from Derived class " );
    }
    public void methodOne()
    {
        System.out.println("methodOne from Derived class");      
    }
    public void methodThree()
    {
        System.out.println("methodThree from Derived class");
    }    
}

    

Driver/Test class

public class BaseDerivedTest
{
    public static void main(String [] args)
    {
        Base b = new Derived();
        b.methodOne();
        b.methodTwo();
        //b.methodThree(); ERROR
        System.out.println("*** Derived ****");
        Derived c = (Derived)b;
        c.methodThree();
        Derived d = new Derived();
        d.methodOne(); 
        d.methodTwo();
        d.methodThree();
    }
}

Include these three classes in your project. Run the driver.

Study the code and the output from the driver class. Use the output to make conclusions based on the following:
1. Do you see a pattern in the order in which the constructor and methods are called? Clearly explain
2. What criteria does the order depend on?
3. Explain how late binding, Polymorphism has a role in the behavior.
Note: Include the output in your submission.

In preparation for the test on Monday work on these assignments:
Self-Review 7.1 through 7.8

Chapter 7: Designing for Inheritance and Interfaces

January 13th, 2017

Interface Hierarchies

  • The concept of inheritance can be applied to interfaces as well as classes.
  • One interface can be derived from another interface.
  • These relationships can form an interface hierarchy, which is similar to a class hierarchy.
  • When a parent interface is used to derive a child interface, the child inherits all abstract methods and constants of the parent.
  • Any class that implements the child interface must implement all of the methods.
  • There are no visibility issues when dealing with inheritance between interfaces (as there are with protected and private members of a class), because all members of an interface are public.
  • Class hierarchies and interface hierarchies do not overlap. That is, an interface cannot be used to derive a class, and a class cannot be used to derive an interface.

Designing for inheritance
▪ Every derivation should be an is-a relationship. The child should be a more specific version of the parent.
▪ Design a class hierarchy to capitalize on reuse, and potential reuse in the future.
▪ As classes and objects are identified in the problem domain, find their commonality. Push common features as high in the class hierarchy as appropriate for consistency and ease of maintenance.
▪ Override methods as appropriate to tailor or change the functionality of a child.
▪ Add new variables to the child class as needed, but don’t shadow (redefine) any inherited variables.
▪ Allow each class to manage its own data. Therefore use the super reference to invoke a parent’s constructor and to call overridden versions of methods if appropriate.
▪ Use interfaces to create a class that serves multiple roles (simulating multiple inheritance).
▪ Design a class hierarchy to fit the needs of the application, with attention to how it may be useful in the future.
▪ Even if there are no current uses for them, override general methods such as toString and equals appropriately in child classes so that the inherited versions don’t cause unintentional problems later.
▪ Use abstract classes to specify a common class interface for the concrete classes lower in the hierarchy.
▪ Choosing which classes and methods to make abstract is an important part of the design process. You should make such choices only after careful consideration. By using abstract classes wisely, you can create flexible, extensible software designs.
▪ Use visibility modifiers carefully to provide the needed access in derived classes without violating encapsulation.
▪ Using the final modifier to restrict inheritance abilities is a key design decision.

Chapter 7: Inheritance – Student

Inheritance – Student Exercise
student
Use this implementation of Student and StudentAthlete ADTs to show inheritance concepts.

  1. Describe what the Student ADT looks like:
    A good description should include the name of the instance fields, whether the ADT has constructor(s), the methods’ purpose, and names.
  2. public class Student
    {
       private String name;
       private int numCourses;
    
       //-----------------------------------------------------------------
       //  Sets up a student with the specified name and number of
       //  courses.
       //-----------------------------------------------------------------
       public Student (String studentName, int courses)
       {
          name = studentName;
          numCourses = courses;
       }
    
       //-----------------------------------------------------------------
       //  Returns information about this student as a string.
       //-----------------------------------------------------------------
       public String toString()
       {
          String result = "Student name: " + name + "\n";
    
          result += "Number of courses: " + numCourses;
    
          return result;
       }
    }
    
  3. Describe what the StudentAthlete ADT looks like:
    A good description should include the name of the instance fields, whether the ADT has constructor(s), the methods’s purpose, and names.
    Mostly clearly identify attributes, any overridden methods, any methods that belong to the child class. As a final sentence describe the relationship between Student and StudentAthlete.
  4. //********************************************************************
    //  StudentAthlete.java       Author: Lewis/Loftus/Cocking
    //
    //  Represents a student athlete who plays a sports team for the school.
    //  Used to demonstrate inheritance.
    //********************************************************************
    
    public class StudentAthlete extends Student
    {
       private String sport;
    
       //-----------------------------------------------------------------
       //  Sets up the student athlete using the specified information.
       //-----------------------------------------------------------------
       public StudentAthlete (String studentName, int courses,
                           String sportName)
       {
          super (studentName, courses);
    
          sport = sportName;
       }
    
       //-----------------------------------------------------------------
       //  Returns a description of this graduate student as a string.
       //-----------------------------------------------------------------
       public String toString()
       {
          String result = super.toString();
    
          result += "\nSport: " + sport;
    
          return result;
       }
    }
    
    
    
  5. Describe the Academia driver class.
  6. //********************************************************************
    //  Academia.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the use of methods inherited from the Object class.
    //********************************************************************
    
    public class Academia
    {
       //-----------------------------------------------------------------
       //  Creates objects of two student types, prints some information
       //  about them, then checks them for equality.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          Student Frank = new Student ("Frank", 5);
          StudentAthlete Suki = new StudentAthlete ("Suki", 4, "Soccer");
    
          System.out.println (Frank);
          System.out.println ();
    
          System.out.println (Suki);
          System.out.println ();
    
          if (! Frank.equals(Suki))
             System.out.println ("These are two different students.");
       }
    }
    
    
    
  7. Add accessor and mutator methods for the studentName and sportName. NOTE: do not change any visibility specifier.
  8. In the Academia driver class, include calls to the methods you just implemented.

All source: Java Software Solutions by Lewis, Loftus and Cocking

Chapter 7: Inheritance – Outline of Concepts

Inheritance
Notes

  • Inheritance is the process of deriving a new class from an existing one.
  • One purpose of inheritance is to reuse existing software.
  • The original class is called the parent class, superclass, or base class.
  • Inheritance creates an “is-a” relationship between the parent and child classes.
  • Java uses the reserved word extends to indicate that a new class is being derived from an existing class.
  • Inheritance is a one-way street.

An example:

Screen Shot 2014-01-21 at 12.40.23 AM

A UML class diagram showing an inheritance relationship

public class Words
{
   //-----------------------------------------------------------------
   //  Instantiates a derived class and invokes its inherited and
   //  local methods.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Dictionary webster = new Dictionary();

      System.out.println ("Number of pages: " + webster.getPages());

      System.out.println ("Number of definitions: " +
                          webster.getDefinitions());

      System.out.println ("Definitions per page: " +
                          webster.computeRatio());
   }
}

public class Book
{
   protected int pages = 1500;

   //----------------------------------------------------------------
   //  Pages mutator.
   //----------------------------------------------------------------
   public void setPages (int numPages)
   {
      pages = numPages;
   }

   //----------------------------------------------------------------
   //  Pages accessor.
   //----------------------------------------------------------------
   public int getPages ()
   {
      return pages;
   }
}
public class Dictionary extends Book
{
   private int definitions = 52500;

   //-----------------------------------------------------------------
   //  Prints a message using both local and inherited values.
   //-----------------------------------------------------------------
   public double computeRatio ()
   {
      return (double) definitions/pages;
   }

   //----------------------------------------------------------------
   //  Definitions mutator.
   //----------------------------------------------------------------
   public void setDefinitions (int numDefinitions)
   {
      definitions = numDefinitions;
   }

   //----------------------------------------------------------------
   //  Definitions accessor.
   //----------------------------------------------------------------
   public int getDefinitions ()
   {
      return definitions;
   }
}

Visibility Modifiers

  • Private methods and variables of the parent class cannot be referenced in the child class or through an object of the child class.
  • Public visibility allows a derived class to reference it, but violates the principle of encapsulation.
  • Protected visibility allows the class to retain some encapsulation properties.
  • Protected visibility provides the best possible encapsulation that permits inheritance. However, the encapsulation is not as tight as if the variable or method were declared private, but it is better than if it were declared public.
  • Modifiers list:
    • public – visible anywhere
    • protected – can only be applied to inner classes. Visible to any classes in the package and to children classes.
    • private – can only be applied to inner classes. Visible enclosing class only.
    • no modifier – default – visible to any classes in the same package.
  • For the AP Computer Science A Exam a design question may required a student to develop a solution that includes all data declared private.

The Super keyword

  • The reserved word super can be used in a class to refer to its parent class.
  • Using the super reference, we can access a parent’s members.
  • Like the this reference, what the word super refers to depends on the class in which it is used.
  • A parent’s constructor can be invoked using the super reference. ( First line in the constructor )
  • If no such call exists, Java will automatically make a call to super() at the beginning of the constructor.
  • The super reference can also be used to reference other variables and methods defined in the parent’s class.
  • The visibility modifiers determine whether a variable or method is inherited into a subclass. If a variable or method is inherited, it can be referenced directly in the child class by name, as if it were declared locally in the child class.
  • However, all variables and methods in a parent class exist for an object of a child class, even though they can’t be referenced directly. They can, however, be referenced indirectly.
  • All members of a superclass exist for a subclass, but they are not necessarily inherited. Only inherited members can be referenced by name in the subclass.
public class Words2
{
   //-----------------------------------------------------------------
   //  Instantiates a derived class and invokes its inherited and
   //  local methods.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Dictionary2 webster = new Dictionary2 (1500, 52500);

      System.out.println ("Number of pages: " + webster.getPages());

      System.out.println ("Number of definitions: " +
                          webster.getDefinitions());

      System.out.println ("Definitions per page: " +
                          webster.computeRatio());
   }
}


public class Book2
{
   protected int pages;

   //----------------------------------------------------------------
   //  Constructor: Sets up the book with the specified number of
   //  pages.
   //----------------------------------------------------------------
   public Book2 (int numPages)
   {
      pages = numPages;
   }

   //----------------------------------------------------------------
   //  Pages mutator.
   //----------------------------------------------------------------
   public void setPages (int numPages)
   {
      pages = numPages;
   }

   //----------------------------------------------------------------
   //  Pages accessor.
   //----------------------------------------------------------------
   public int getPages ()
   {
      return pages;
   }
}


public class Dictionary2 extends Book2
{
   private int definitions;

   //-----------------------------------------------------------------
   //  Constructor: Sets up the dictionary with the specified number
   //  of pages and definitions.
   //-----------------------------------------------------------------
   public Dictionary2 (int numPages, int numDefinitions)
   {
      super(numPages);

      definitions = numDefinitions;
   }

   //-----------------------------------------------------------------
   //  Prints a message using both local and inherited values.
   //-----------------------------------------------------------------
   public double computeRatio ()
   {
      return (double) definitions/pages;
   }

   //----------------------------------------------------------------
   //  Definitions mutator.
   //----------------------------------------------------------------
   public void setDefinitions (int numDefinitions)
   {
      definitions = numDefinitions;
   }

   //----------------------------------------------------------------
   //  Definitions accessor.
   //----------------------------------------------------------------
   public int getDefinitions ()
   {
      return definitions;
   }
}



Overriding Notes

  • A child class can override (redefine) the parent’s definition of an inherited 
method.
  • Constructors, however, are not inherited and cannot be overridden.
  • Method overriding is a key element in object-oriented design.
  • Method overriding allows two objects that are related by inheritance to use the same naming conventions for methods that accomplish the same general task in different ways.
  • A method can be defined with the final modifier. A child class cannot override a final method. This technique is used to ensure that a derived class uses a particular definition of a method.
  • The final modifier can also be applied to an entire class. A final class cannot be extended at all.

Shadowing

  • If a variable of the same name is declared in a child class, it is called a shadow variable.
  • To avoid confusion and logical errors, shadowing variables should be avoided.

Class Hierarchy

Screen Shot 2014-01-21 at 12.40.50 AM

A UML class diagram showing a class hierarchy

  • The child of one class can be the parent of one or more other classes, creating a class hierarchy.
  • Common features should be located as high in a class hierarchy as is reasonably possible.
  • All Java classes are derived, directly or indirectly, from the Object class.
  • The toString and equals methods are inherited by every class in every 
Java program.
  • Inheritance can be applied to interfaces so that one interface can be derived from another.
  • Private members are inherited by the child class, but cannot be referenced directly by name. They may be used indirectly, however.
  • Java’s approach to inheritance is called single inheritance.

Abstract Classes

  • It represents a concept on which other classes can build their definitions.An abstract class cannot be instantiated.
  • A class derived from an abstract parent must override all of its parent’s abstract methods, or the derived class will also be considered abstract.
  • An abstract class is similar to an interface in some ways.
  • However, unlike interfaces, an abstract class can contain methods that are not abstract.
  • An abstract class can also contain data declarations other than constants.
  • A class is declared as abstract by including the abstract modifier in the class header.
  • Any class that contains one or more abstract methods must be declared as abstract.
  • In abstract classes (unlike interfaces), the abstract modifier must be applied to each abstract method.
  • A class declared as abstract does not have to contain abstract methods.
  • Abstract classes serve as placeholders in a class hierarchy.
  • If a child of an abstract class does not give a definition for every abstract method that it inherits from its parent, then the child class is also considered abstract.
  • Note that it would be a contradiction for an abstract method to be modified as final or static.
  • Because abstract methods have no implementation, an abstract static method would make no sense.

Homework:
Read pages 382 through 419

giphy

All source: Java Software Solutions by Lewis, Loftus and Cocking

Chapter 6: The Selection Sort


Classwork:

Video from Professor Sedgewick on edmodo.com

Videos you can watch at home:



Sorts: The Selection Sort

selectionSort

selectionSortCode

selectionCodeAndVisual

Time efficiency and the Big-Oh notation

Homework:
1. Tell the story of the Selection Sort to someone who knows no computer programming.
2. Show the sequence of changes the selection sort algorithm makes to the following list of numbers:
5 7 1 8 2 4 3

3. Write the code for the Selection Sort in a static function in a tester/driver class, SortTester.java.
Assign random integers in the range of 15 to 35 to an array of 20 “int” elements.
Display the array.
Sort it with the Selection Sort and display it again.

Chapter 6: The Insertion Sort


Sorts: The Insertion Sort

insertionSort

https://www.youtube.com/watch?v=lCDZ0IprFw4

//********************************************************************
//  Sorts.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the selection sort and insertion sort algorithms,
//  as well as a generic object sort.
//********************************************************************
@SuppressWarnings("unchecked")
public class Sorts
{
   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using the selection
   //  sort algorithm.
   //-----------------------------------------------------------------
   public static void selectionSort (int[] numbers)
   {
      int min, temp;

      for (int index = 0; index < numbers.length-1; index++)
      {
         min = index;
         for (int scan = index+1; scan < numbers.length; scan++)
            if (numbers[scan] < numbers[min])
               min = scan;

         // Swap the values
         temp = numbers[min];
         numbers[min] = numbers[index];
         numbers[index] = temp;
      }
   }

   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using the insertion
   //  sort algorithm.
   //-----------------------------------------------------------------
   public static void insertionSort (int[] numbers)
   {
      for (int index = 1; index < numbers.length; index++)
      {
         int key = numbers[index];
         int position = index;

         // shift larger values to the right
         while (position > 0 && numbers[position-1] > key)
         {
            numbers[position] = numbers[position-1];
            position--;
         }
            
         numbers[position] = key;
      }
   }

   //-----------------------------------------------------------------
   //  Sorts the specified array of objects using the insertion
   //  sort algorithm.
   //-----------------------------------------------------------------
   public static void insertionSort (Comparable[] objects)
   {
      for (int index = 1; index < objects.length; index++)
      {
         Comparable key = objects[index];
         int position = index;

         // shift larger values to the right
         while (position > 0 && objects[position-1].compareTo(key) > 0)
         {
            objects[position] = objects[position-1];
            position--;
         }
            
         objects[position] = key;
      }
   }
}

Classwork:
1. Tell the story of the Insertion Sort to someone who knows no computer programming.
2. Show the sequence of changes the insertion sort algorithm makes to the following list of numbers:
5 7 1 8 2 4 3

Assignments:
MC 6.6
T/F 6.8 and 6.10
SA 6.4 and 6.5
Programming Projects 6.11:
Modify the Tunes program so that it keeps the CDs sorted by title. Use the general object sort defined in the Sorts class from this chapter.

Programming Projects 6.12
Modify the Sorts class to include an overloaded version of the SelectionSort method that performs a general object sort. Modify the SortPhoneList program to test the new sort.

Chapter 6: ArrayLists<E>()

ArrayLists

ArrayLists, type parameter, and for-each loop example

import java.util.ArrayList;

/**
   This bank contains a collection of bank accounts.
*/
public class Bank
{   
   /**
      Constructs a bank with no bank accounts.
   */
   public Bank()
   {
      accounts = new ArrayList();
   }

   /**
      Adds an account to this bank.
      @param a the account to add
   */
   public void addAccount(BankAccount a)
   {
      accounts.add(a);
   }
   
   /**
      Gets the sum of the balances of all accounts in this bank.
      @return the sum of the balances
   */
   public double getTotalBalance()
   {
      double total = 0;
      for (BankAccount a : accounts)
      {
         total = total + a.getBalance();
      }
      return total;
   }

   /**
      Counts the number of bank accounts whose balance is at
      least a given value.
      @param atLeast the balance required to count an account
      @return the number of accounts having least the given balance
   */
   public int count(double atLeast)
   {
      int matches = 0;
      for (BankAccount a : accounts)
      {
         if (a.getBalance() >= atLeast) matches++; // Found a match
      }
      return matches;
   }

   /**
      Finds a bank account with a given number.
      @param accountNumber the number to find
      @return the account with the given number, or null if there
      is no such account
   */
   public BankAccount find(int accountNumber)
   {
      for (BankAccount a : accounts)
      {
         if (a.getAccountNumber() == accountNumber) // Found a match
            return a;
      } 
      return null; // No match in the entire array list
   }

   /**
      Gets the bank account with the largest balance.
      @return the account with the largest balance, or null if the
      bank has no accounts
   */
   public BankAccount getMaximum()
   {
      if (accounts.size() == 0) return null;
      BankAccount largestYet = accounts.get(0);
      for (int i = 1; i < accounts.size(); i++) 
      {
         BankAccount a = accounts.get(i);
         if (a.getBalance() > largestYet.getBalance())
            largestYet = a;
      }
      return largestYet;
   }

   private ArrayList accounts;
}

ArrayLists, type parameter, for-each loop and Iterator another example

/** 
 * mrs.e
 * 12/14/2018
 * 
 * ArrayLists
 * for-each loop
 * Iterator
 * 
 * */

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListIterator 
{
   public static void main( String[] args )
   {
      // add elements to an ArrayList
      String[] pets = { "Puppy", "Kitten", "Gerbil", "Bunny", "Ferret" };
      ArrayList< String > aList = new ArrayList< String >();      

      for ( String pet : pets )
         aList.add( pet ); // for each loop - don't change the ArrayList   

      // add elements in removePets array to removeList
      String[] removePets = { "Gerbil", "Bunny" };
      ArrayList< String > removeList = new ArrayList< String >();

      for ( String pet : removePets )
         removeList.add( pet ); 

      // print items of the list
      System.out.println( "ArrayList: " );

      for ( int count = 0; count < aList.size(); count++ )
         System.out.printf( "%s ", aList.get( count ) );

      // remove from list the pets contained in removeList
      removePets( aList, removeList );

      // print itmes of the list 
      System.out.println( "\n\nArrayList after calling removePets: " );

      for ( String pet : aList )
         System.out.printf( "%s ", pet );
   } // end main

   // remove pets in collection2 found in collection1
   private static void removePets( ArrayList< String > collection1, 
      ArrayList< String > collection2 )
   {
      // get iterator
      Iterator< String > iterator = collection1.iterator(); 

      // loop while collection has items
      while ( iterator.hasNext() )         
      {
         if ( collection2.contains( iterator.next() ) )
            iterator.remove(); // remove current pet
      } // end while
   } // end method removePets
} // end class ArrayListIterator

indexOf and lastIndexOf example from http://www.dotnetperls.com/arraylist-java

import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

    ArrayList list = new ArrayList<>();
    list.add(101);
    list.add(100);
    list.add(99);
    list.add(100);
    list.add(99);

    // Search for values.
    int index = list.indexOf(100);
    int lastIndex = list.lastIndexOf(100);
    int notFound = list.indexOf(200);

    // Display results.
    System.out.println(index);     // 1
    System.out.println(lastIndex); // 3
    System.out.println(notFound);  // -1
    }
}

Output

1
3
-1

§ § § § § §

More advanced topics in this link. (Optional)

ListIterator, indexOf, Iterator, List Interface
Screen Shot 2014-12-15 at 9.05.33 PM

[collapse]

Screen Shot 2014-12-11 at 9.19.49 PM

Screen Shot 2014-12-11 at 9.26.39 PM

ArrayList<E>()

Constructs an empty list with an initial capacity of ten.

Screen Shot 2014-12-11 at 9.30.09 PM

boolean add(E obj)
Appends the specified element to the end of this list.

void add(int index, E obj)
Inserts the specified element at the specified position in this list.

E get(int index)
Returns the element at the specified position in this list.

int indexOf(Object obj)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

boolean isEmpty()
Returns true if this list contains no elements.

int size()
Returns the number of elements in this list.

ListIterator<E> listIterator()

Returns a list iterator over the elements in this list (in proper sequence).

E remove(int index)
Removes the element at the specified position in this list.

boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.

//********************************************************************
//  DestinysChild.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a ArrayList object.
//********************************************************************

import java.util.ArrayList;

public class DestinysChild
{
   //-----------------------------------------------------------------
   //  Stores and modifies a list of band members.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      ArrayList band = new ArrayList();

      band.add ("Michelle");
      band.add ("Kelly");
      band.add ("Beyonce");
      band.add ("Farrah");

      System.out.println (band);

      int location = band.indexOf ("Farrah");
      band.remove (location);

      System.out.println (band);
      System.out.println ("At index 1: " + band.get(1));

      System.out.println (band);
      System.out.println ("Size of the band: " + band.size());
   }
}


[Michelle, Kelly, Beyonce, Farrah]
[Michelle, Kelly, Beyonce]
At index 1: Kelly
[Michelle, Kelly, Beyonce]
Size of the band: 3

Two ways to iterate through the elements of a collection in java:

  1. By Iterator interface.
  2. By for-each loop.
//********************************************************************
//  Recipe.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a ListIterator to iterate through the
//  elements of an ArrayList.
//********************************************************************

import java.util.ArrayList;
import java.util.ListIterator;

public class Recipe
{
   //-----------------------------------------------------------------
   //  Stores and then prints a list of ingredients for a recipe.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      ArrayList ingredients = new ArrayList();

      ingredients.add ("flour");
      ingredients.add ("sugar");
      ingredients.add ("cocoa");
      ingredients.add ("oil");
      ingredients.add ("butter");
      ingredients.add ("eggs");
      ingredients.add ("baking soda");

      System.out.println ("To make a chocolate cake, use the following " +
         ingredients.size() + " ingredients:");

      // traversing ArrayList by Iterator
      ListIterator iterator = ingredients.listIterator(); 
      while (iterator.hasNext())
         System.out.println(iterator.next());

      // traversing ArrayList using the "for-each" loop
       for(String obj:ingredients)  
          System.out.println(obj);  

   }
}

To make a chocolate cake, use the following 7 ingredients:
flour
sugar
cocoa
oil
butter
eggs
baking soda

Classwork/Homework:
1. Create a class DataSet of BankAccounts. The constructor creates an ArrayList of BankAccount(s). Write the test class to add, delete and print (use the for-each loop) bank accounts. Your driver should have at least 3 BankAccount objects. Make any changes necessary to have the DataSet ADT implemented with an ArrayList. Also, change the comments to fit the modifications to the it.

DataSet with ArrayList

/**
   Computes the average of a set of data values.
*/
public class DataSet
{
   /**
      Constructs an empty data set with no BankAccount objects.
   */
   public DataSet()
   {
      sum = 0;
      count = 0; // Warning: Is "count" necessary?
      maximum = 0; // Warning: this should not be a numeric type!!
      // create an object of the ArrayList dataSet
   }

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

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

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

   /**
      Prints the balance for each element of the added data in the ArrayList.// Warning
      @return the average or 0 if no data has been added
   */
   public void printDataSet()
   {
     // implement the code to print the elements of the ArrayList datSet. Add more specific comments
     // use the for-each loop
   }

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

[collapse]
  1. Create a class Purse (see below) that contains an ArrayList of Coin(s). Write the test class to add, delete, and print coins. Make any changes necessary to have the Purse class implemented with an ArrayList. Also, change the comments to fit the modifications to the ADT.
/**
   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;
   }

   public boolean equals(Object otherObject)
   {  
      Coin other = (Coin)otherObject;
      return name.equals(other.name) 
         && value == other.value; 
   }

   private double value;
   private String name;
}

Modify the Purse class to be implemented with ArrayList<Coin> and to use a for-each loop.
Implement the following methods in the Purse class:

   /**
      Counts the number of coins in the purse
      @return the number of coins
   */
   public int count()
   {
     
   }

   /**
      Tests if the purse has a coin that matches
      a given coin.
      @param aCoin the coin to match
      @return true if there is a coin equal to aCoin
   */
   public boolean find(Coin aCoin)
   {

   }

   /**
      Counts the number of coins in the purse that match
      a given coin.
      @param aCoin the coin to match
      @return the number of coins equal to aCoin
   */
   public int count(Coin aCoin)
   {

   }

   /**
      Finds the coin with the largest value. 
      (Precondition: The purse is not empty)
      @return a coin with maximum value in this purse
   */
   pulic Coin getMaximum()
   {

   }

NOTE: Use the “for-each” loop in the implementation.