Anda di halaman 1dari 18

Lab 3: Inheritance

Q1: please fill in the empty place (yellow), and run the code to get the output.
//********************************************************************
// FoodAnalyzer.java Author: Lewis/Loftus
// Demonstrates indirect access to inherited private members.
//********************************************************************

public class FoodAnalyzer


{
//-----------------------------------------------------------------
// Instantiates a Pizza object and prints its calories per
// serving.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Pizza special = new Pizza (275);

System.out.println ("Calories per serving: " +


special.caloriesPerServing());
}
}

//********************************************************************
// Pizza.java Author: Lewis/Loftus
//
// Represents a pizza, which is a food item. Used to demonstrate
// indirect referencing through inheritance.
1

//********************************************************************
Page
public class Pizza extends FoodItem
{
//-----------------------------------------------------------------
// Sets up a pizza with the specified amount of fat (assumes
// eight servings).
//-----------------------------------------------------------------
public Pizza (int fatGrams)
{
super (fatGrams, 8);
}
}

//********************************************************************
// FoodItem.java Author: Lewis/Loftus
//
// Represents an item of food. Used as the parent of a derived class
// to demonstrate indirect referencing.
//********************************************************************

public class FoodItem


{
final private int CALORIES_PER_GRAM = 9;
private int fatGrams;
protected int servings;

//-----------------------------------------------------------------
2

// Sets up this food item with the specified number of fat grams
Page
// and number of servings.
//-----------------------------------------------------------------
public FoodItem (int numFatGrams, int numServings)
{
fatGrams = numFatGrams;
servings = numServings;

//-----------------------------------------------------------------
// Computes and returns the number of calories in this food item
// due to fat.
//-----------------------------------------------------------------
private int calories()
{
return fatGrams * CALORIES_PER_GRAM;
}

//-----------------------------------------------------------------
// Computes and returns the number of fat calories per serving.
//-----------------------------------------------------------------
public int caloriesPerServing()
{
return (calories() / servings);

}
}
3
Page
Run them and the Output: _______ Calories per serving: 309

Q2: please fill in the empty place (yellow), and run the code to get the output.
//********************************************************************
// OffCenter.java Author: Lewis/Loftus
//
// Demonstrates the use of an event adatpter class.
//********************************************************************

import javax.swing.*;

public class OffCenter


{
//-----------------------------------------------------------------
4
Page

// Creates the main frame of the program.


//-----------------------------------------------------------------
public static void main (String[] args)
{
JFrame frame = new JFrame ("Off Center");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new OffCenterPanel());
frame.pack();
frame.setVisible(true);
}
}
//********************************************************************
// OffCenterPanel.java Author: Lewis/Loftus
//
// Represents the primary drawing panel for the OffCenter program.
//********************************************************************

import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;

public class OffCenterPanel extends JPanel


{
private final int WIDTH=300, HEIGHT=300;
5

private DecimalFormat fmt;


Page
private Point current;
private int centerX, centerY;
private double length;

//-----------------------------------------------------------------
// Constructor: Sets up the panel and necessary data.
//-----------------------------------------------------------------
public OffCenterPanel()
{
addMouseListener (new OffCenterListener());

centerX = WIDTH / 2;
centerY = HEIGHT / 2;

fmt = new DecimalFormat ("0.##");

setPreferredSize (new Dimension(WIDTH, HEIGHT));


setBackground (Color.yellow);
}

//-----------------------------------------------------------------
// Draws a line from the mouse pointer to the center point of
// the applet and displays the distance.
//-----------------------------------------------------------------
public void paintComponent (Graphics page)
{
super.paintComponent (page);
6
Page
page.setColor (Color.black);
page.drawOval (centerX-3, centerY-3, 6, 6);

if (current != null)
{
page.drawLine (current.x, current.y, centerX, centerY);
page.drawString ("Distance: " + fmt.format(length), 10, 15);
}
}

//*****************************************************************
// Represents the listener for mouse events. Demonstrates the
// ability to extend an adaptor class.
//*****************************************************************
private class OffCenterListener extends MouseAdapter
{
//--------------------------------------------------------------
// Computes the distance from the mouse pointer to the center
// point of the applet.
//--------------------------------------------------------------
public void mouseClicked (MouseEvent event)
{
current = event.getPoint();
length = Math.sqrt(Math.pow((current.x-centerX), 2) +
Math.pow((current.y-centerY), 2));
repaint();
}
7

}
Page
}
Run them and the Output: ____________________________
Note: Screenshot is down

8
Page
Q3: please fill in the empty place (red), and run the code to get the output.
//********************************************************************
// Rebound.java Author: Lewis/Loftus
//
// Demonstrates an animation and the use of the Timer class.
//********************************************************************

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Rebound


{
//-----------------------------------------------------------------
// Displays the main frame of the program.
//-----------------------------------------------------------------
public static void main (String[] args)
{
JFrame frame = new JFrame ("Rebound");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new ReboundPanel());

frame.pack();
frame.setVisible(true);
}
}
9
Page
//********************************************************************
// ReboundPanel.java Author: Lewis/Loftus
//
// Represents the primary panel for the Rebound program.
//********************************************************************

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ReboundPanel extends JPanel


{
private final int WIDTH = 300, HEIGHT = 100;
private final int DELAY = 20, IMAGE_SIZE = 35;

private ImageIcon image;


private Timer timer;
private int x, y, moveX, moveY;

//-----------------------------------------------------------------
// Sets up the panel, including the timer for the animation.
//-----------------------------------------------------------------
public ReboundPanel()
{
timer = new Timer(DELAY, new ReboundListener());

image = new ImageIcon ("happyFace.gif");


10
Page
x = 0;
y = 40;
moveX = moveY = 3;

setPreferredSize (new Dimension(WIDTH, HEIGHT));


setBackground (Color.black);
timer.start();
}

//-----------------------------------------------------------------
// Draws the image in the current location.
//-----------------------------------------------------------------
public void paintComponent (Graphics page)
{
super.paintComponent (page);
image.paintIcon (this, page, x, y);
}

//*****************************************************************
// Represents the action listener for the timer.
//*****************************************************************
private class ReboundListener implements ActionListener
{
//--------------------------------------------------------------
// Updates the position of the image and possibly the direction
// of movement whenever the timer fires an action event.
11

//--------------------------------------------------------------
Page
public void actionPerformed (ActionEvent event)
{
x += moveX;
y += moveY;

if (x <= 0 || x >= WIDTH-IMAGE_SIZE)


moveX = moveX * -1;

if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)


moveY = moveY * -1;

repaint();
}
}
}

Run them and the Output: ____________________________


Note: Down below is the screenshot of the ouput

12
Page
Q4: Design and implement a project: (fill in the yellow fields with one row or multiple rows
codes), and run the code to get the output.
Design and implement a class called MonetaryCoin that is derived from the Coin class (see
below). Store a value in the monetary coin that represents its value and add a method that returns
its value. Creat a main driver class (MonetaryCoinDriver) to instantiate and compute the sum of
several MonetaryCoin objects. Demonstrate that a monetary coin inherits its parents ability to be
flipped.
//********************************************************************
13

// MonetaryCoinDriver.java Author: Lewis/Loftus


Page
// MonetaryCoinDriver==> MonetaryCoin === > Coin
// Solution to Programming Project 9.1
//********************************************************************

public class MonetaryCoinDriver


{
//-----------------------------------------------------------------
// Demonstrates the use of a MonetaryCoin derived from Coin.
//-----------------------------------------------------------------
public static void main (String[] args)
{
MonetaryCoin[] coins = new MonetaryCoin[7];

coins[0] = new MonetaryCoin(1);


coins[1] = new MonetaryCoin(5);
coins[2] = new MonetaryCoin(10);
coins[3] = new MonetaryCoin(25);
coins[4] = new MonetaryCoin(50);
coins[5] = new MonetaryCoin(100);
coins[6] = new MonetaryCoin(100);
// flip all of the coins
for (MonetaryCoin coin : coins)
coin.flip();
// compute total value
int sum = 0;
for (MonetaryCoin coin : coins)
sum += coin.getValue();
// print the coins
for (MonetaryCoin coin : coins)
System.out.println (coin);

System.out.println ("\nTotal Value: " + sum); }


14

}
Page
//********************************************************************
// Coin.java Author: Lewis/Loftus
//********************************************************************

public class Coin


{
public final int HEADS = 0;
public final int TAILS = 1;

private int face;

//-----------------------------------------------------------------
// Sets up the coin by flipping it initially.
//-----------------------------------------------------------------
public Coin ()
{
flip();
}

//-----------------------------------------------------------------
// Flips the coin by randomly choosing a face value.
//-----------------------------------------------------------------
public void flip ()
{
face = (int) (Math.random() * 2);
}
15
Page
//-----------------------------------------------------------------
// Returns true if the current face of the coin is heads.
//-----------------------------------------------------------------
public boolean isHeads ()
{
return (face == HEADS);
}

//-----------------------------------------------------------------
// Returns the current face of the coin as a string.
//-----------------------------------------------------------------
public String toString()
{
String faceName;

if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";

return faceName;
}
}

//********************************************************************
// MonetaryCoin.java
//********************************************************************
16

import java.text.*;
Page
public class MonetaryCoin extends Coin
{
private int coinValue;
NumberFormat money = NumberFormat.getCurrencyInstance();
public MonetaryCoin(int value)
{
coinValue = value;
}

public int getValue()


{
return coinValue;
}
public String toString()
{
String coinString;
coinString = (super.toString() + " " +
money.format((double)coinValue/100));
return coinString;
}
}
Run them and the Output: ____________________________
Heads $0.01
Heads $0.05
Heads $0.10
Tails $0.25
Heads $0.50
Tails $1.00
Heads $1.00

Total Value: 291

Note:
Down is the screenshot

17
Page
Page
18

Anda mungkin juga menyukai