Title: Polymorphism
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Polymorphism

We will go over Sale.java, Discount.java to go over Late Binding and Early Binding concepts

Basics

1. Late Binding concepts Take a look at Sales.java and DiscountSale.java -- not the "bill" method which is called from "lessThan" and "equalDeals" .
2. Keyword final - on a class it means that you can't extend it. On a method, it means that the method can't be overridden.
3. Downcasting/Upcasting - consider:


  Sale saleVariable;
  DiscountSale discountVariable = new DiscountSale("paint", 15, 10);
  saleVariable = discountVariable;   // Upcasting
  System.out.println(saleVariable.toString()); // Java calls toString in DiscountSale

  DiscountSale discountVariable2 = (DiscountSale) saleVariable; // Downcasting: This should actually work
  //
Sale saleVariable = new SaleVariable("Shovel", 1.2);
Discount discountVariable2 = (DiscountSale)saleVariable2; // Downcasting that will not work at runtime

Self-Test Exercises:

1. Explain the difference between the terms late binding and polymorphism
2. Suppose you modify the definitions of the class Sale by adding the modifier final to the definition of the bill. How would that change the output of the program in LateBindingDemo.
3. Would it be legal to add the following method definition to the class DiscountSale?


  public static boolean isAGoodBuy(Sale theSale)
  {
      return (theSale.getDiscount() > 20);
  }


4. Complete the definition of the method equals for the class DiscountSale
5. Would it be legal to add the following method definition to the class DiscountSale? What about adding it to the class Sale?


	public static void showDiscount(Sale object)
	{
	    System.out.println("Discount="+ object.getDiscount());
	}
	

6. What output is produced by the following code?


  Sale someObject = new DiscountSale("map", 5, 0);
  DiscountSale ds = new DiscountSale();
  if (someObject instanceof DiscountSale)
  {
      ds = (DiscountSale)someObject;
	  System.out.println("ds was changed to " + someObject);
  }
  else
      System.out.println("ds was not changed.");


7. What output is produced by the following code?


  Sale someObject = new Sale("map", 5);
  DiscountSale ds = new DIscountSale();
  if (someObject instanceof DiscountSale)
  {
      ds = (DiscountSale)someObject;
	  System.out.println("ds was changed to " + someObject);
  }
  else
      System.out.println("ds was not changed.");


8. Suppose we removed the qualifier static from the method announcement() in both Sale and DiscountSale. What would be the output produced by the following code


	Sale s = new Sale();
	DIscountSale discount = new DiscountSale();
	s.announcement();
	discount.announcement();
	System.out.println("no surprises so far, but wait.");
	
	Sale discount2 = discount;
	System.out.println("discount2 is a DiscountSale object in a Sale variable.");
	System.out.println("Which definition of announcement() will it use?");
	discount2.announcement();
	System.out.println(
	    "Did it use the Sale version of announcment()?");
	

Abstract classes

1. Abstract version of Employee.
2. An abstract cannot be constructed. However, it defines a class and typically defines a method that is a placeholder that needs to be overridden by any class that can be constructed.
3. See Employee.java that abstract class and then look at SalariedEmployee, and HourlyEmployee.

Self-Test Exercises:

1. Can a method definition include an invocation of an abstract method?
2. Can you have a variable whose type is an abstract class?
3. Can you have a parameter whose type is an abstract class?
4. Is it legal to have an abstract class in which all methods are abstract?
5. Employee.java is abstract, so it's illegal to say:
Employee joe = new Employee();

So why bother to have any constructors in an abstract class? Aren't they useless?

Shape examples:

We will also use the example of Shape, Oval, Rectangle, Circle, Square to illustrate:

Polymorphism, array of base classes, late-binding properties (computing area);
Shape contains:
x,y,color
area
static int getCount
Derive Rectangle and Oval
w,h added to Rectangle and Oval
Demo calling all of these methods

Demonstrate class that extends JFrame simple drawing.


// a couple routines:
MyDrawing()

{
    super("My First GUI Example");
    setSize(600,500);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
    g.setColor(Color.red);
    g.drawRect(50,70,50,100);
    g.drawOval(100, 200, 100,200);
    g.fillOval(200,200,100,200);
}


Demo Abstract version of Shape.
Starting from last version of Shape, make area abstract and add a method:
public abstract void draw(Graphics g);
Add a method to Shape for setColor(Graphics g)

To the MyDrawing example add:
An Array of Shape and a count
add a method:
public void addShape(Shape s) that does a repaint()
update paint to handle this
Add a main that prompts the user and allows the user to specify objects

Print out the total area of all objects and the counts of all types of objects on the screen with drawString.

Interfaces:

Create an MakesMusic class with methods of:
getType
play

Create an Orchestra.

Change MakeMusic to an abstract class and redo the Orchestra

Change MakeMusic to an Interface and redo the Orchestra

Now add a Singer which extends Person, but implements MakeMusic

Redo the previous Shape, Rectangle, Oval example to work with and Interface of Shape.

One last topic: CopyConstructor versus Clone approach (see CopyingDemo.java)

Exercises:

1. At then end of the chapter (#4) do the Doodlebug game of life.
Set up Abstract Organism, Ant, Predator problem. Use probabilites for birth, isolation death, crowding, predator eating, predator starving(predators can be isolated, but they need to eat after some number of iterations).
Rules:
Ants - every step, Ants try to move
after 3 successive moves, the Ant creates a baby if possible (needs an empty cell)

Predators:
Predators always try to move(if possible), but they will preferrentially move to an adjacent Ant cell to eat it if it is available
If a Predator hasn't eaten in 3 moves, it starves and dies
If a Predator survives for 8 steps, then it creates a baby if possible the same as Ants.

Start the game with 5 predators and 100 Ants

Last Modified: July 14, 2013 4:01 PM