Download LAB 1: INTRODUCTION TO PROGRAMMING

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
LAB 6: OBJECTS AND CLASSES.
Objects of the same type are defined using a common class. A class is a template, blueprint, or
contract that defines what an object’s data fields and methods will be. An object is an instance of a
class. You can create many instances of a class. Creating an instance is referred to as instantiation.
The terms object and instance are often interchangeable.
LAB SHEET 6.1: Defining Classes for Objects, Constructors, Accessing Objects
ESTIMATED TIME
:
1.5 hours
OBJECTIVE
:
To describe objects and classes, and use classes to model objects.
To use UML graphical notations to describe classes and objects.
To create objects using constructors.
To access objects via object reference variables.
To define a reference variable using a reference type.
REQUIREMENTS
:
JCreator 5.00 LE
PROCEDURE
:
Read all the questions and write the program. Then run the program
and get the correct output.
CONCLUSION
:
Students are able to describe objects and classes, use classes to
model objects, use UML graphical notations to describe classes and
objects, create objects using constructors, access objects via object
reference variables and define a reference variable using a reference
type.
DISCUSSION / RESULT / EXERCISE
a) (The Rectangle class) Following the example of the Circle class in slide, design a class
named Rectangle to represent a rectangle. The class contains:





Two double data fields named width and height that specify the width and height of the
rectangle. The default values are 1 for both width and height.
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified width and height.
A method named getArea() that returns the area of this rectangle.
A method named getPerimeter() that returns the perimeter.
Implement the class. Write a test program that creates two Rectangle objects – one with
width 4 and height 40 and the other with width 3.5 and height 35.9. Display the width, height,
area, and perimeter of each rectangle in this order.
public class LabSheet6_1a {
public static void main(String[] args) {
Rectangle myRectangle = new Rectangle(4, 40);
System.out.println(“The area of a rectangle with width ” +
myRectangle.width + “ and height ” +
myRectangle.height + “ is ” + myRectangle.getArea());
1
System.out.println(“The perimeter of a rectangle is ” +
myRectangle.getPerimeter();
Rectangle yourRectangle = new Rectangle(3.5, 35.9);
System.out.println(“The area of a rectangle with width ” +
yourRectangle.width + “ and height ” +
yourRectangle.height + “ is ” + yourRectangle.getArea());
System.out.println(“The perimeter of a rectangle is ” +
yourRectangle.getPerimeter());
}
}
class Rectangle {
// Data members
double width = 1, height = 1;
// Constructor
public Rectangle() {
}
// Constructor
public Rectangle(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
b) (The Stock class) Following the example of the Circle class in slide, design a class named
Stock that contains:






A string data field named symbol for the stock’s symbol.
A string data field named name for the stock’s name.
A double data field named previousClosingPrice that stores the stock price for the
previous day.
A double data field named currentPrice that stores the stock price for the current time.
A constructor that creates a stock with specified symbol and name.
A method named getChangePercent() that return the percentage changed from
previousClosingPrice to currentPrice.
Draw the UML diagram for the class. Implement the class. Write a test program that creates a
Stock object with the stock symbol JAVA, the name Sun Microsystem Inc, and the previous
closing price of 4.5. Set a new current price to 4.35 and display the price-change percentage.
2
Stock
symbol: String
name: String
previousClosingPrice: double
currentPrice: double
Stock(symbol: String, name: String)
getChangePercent(): double
The symbol of this stock.
The name of this stock.
The previous closing price of this stock.
The current price of this stock.
Constructs a stock with a specified symbol and a name.
Returns the percentage of change of this stock.
public class LabSheet6_1b {
public static void main(String[] args) {
Stock stock = new Stock(“JAVA”, “Sun Microsystems Inc.”);
stock.previousClosingPrice = 4.5;
// Set current price
stock.currentPrice = 4.35;
// Display stock info
System.out.println(“Previous Closing Price: ” +
stock.previousClosingPrice);
System.out.println(“Current Price: ” + stock.currentPrice);
System.out.println(“Price Change: ” +
stock.changePercent() * 100 + “%”);
}
}
class Stock {
String symbol;
String name;
double previousClosingPrice;
double currentPrice;
public Stock() {
}
public Stock(String newSymbol, String newName) {
symbol = newSymbol;
name = newName;
}
public double changePercent() {
return (currentPrice – previousClosingPrice) /
previousClosingPrice;
}
}
3
LAB SHEET 6.2: Using Classes from the Java Library
ESTIMATED TIME
:
1.5 hours
OBJECTIVE
:
To use classes Date and Random in the Java library.
REQUIREMENTS
:
JCreator 5.00 LE
PROCEDURE
:
Read all the questions and write the program. Then run the program
and get the correct output.
CONCLUSION
:
Students are able to use classes Date and Random in the Java
library.
DISCUSSION / RESULT / EXERCISE
a) (Using the Date class) Write a program that creates a Date object, sets its elapsed time to
20000, 300000, 40000000, 50000000, 600000000, 7000000000, 80000000000,
900000000000, and displays the date and time using the toString() method, respectively.
import java.util.Date;
public class LabSheet6_2a {
public static void main(String[] args) {
Date date = new Date();
int count = 1;
long time = 10000;
while (count < 10) {
date.setTime(time);
System.out.println(date.toString());
count++;
time *= 10;
}
}
}
b) (Using the Random class) Write a program that creates a Random object with seed 2500 and
displays the first 25 random integers between 0 and 50 using the nextInt(50) method.
import java.util.Random;
public class LabSheet6_2b {
public static void main(String[] args) {
Random random = new Random(1000);
for (int i = 0; i < 50; i++)
System.out.print(random.nextInt(100) + “ ”);
}
}
4
LAB SHEET 6.3: Visibility Modifiers, Data Encapsulation
ESTIMATED TIME
:
3 hours
OBJECTIVE
:
To define private data fields with appropriate get and set methods.
To encapsulate data fields to make classes easy to maintain.
REQUIREMENTS
:
JCreator 5.00 LE
PROCEDURE
:
Read all the questions and write the program. Then run the program
and get the correct output.
CONCLUSION
:
Students are able to define private data fields with appropriate get and
set methods and to encapsulate data fields to make classes easy to
maintain.
DISCUSSION / RESULT / EXERCISE
a) (The Account class) Design a class named Account that contains:











A private int data field named id for the account (default 0).
A private double data field named balance for the account (default 0).
A private double data field named annualInterestRate that stores the current interest
rate (default 0). Assume all accounts have the same interest rate.
A private Date data field named dateCreated that stores the date when the account was
created.
A no-arg constructor that creates a default account.
A constructor that creates an account with the specified id and initial balance.
The accessor and mutator methods for id, balance, and annualInterestRate.
The accessor method for dateCreated.
A method named getMonthlyInterestRate() that returns the monthly interest rate.
A method named withdraw that withdraws a specified amount from the account.
A method named deposit that deposits a specified amount to the account.
Implement the class. Write a test program that creates an Account object with an account ID
of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method
to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the
monthly interest, and the date when this account was created.
public class LabSheet6_3a {
public static void main(String[] args) {
Account account = new Account(1122, 20000);
account.setAnnualInterestRate(4.5);
account.withdraw(2500);
account.deposit(3000);
System.out.println(“Balance is ” + account.getBalance());
System.out.println(“Monthly interest is ” +
account.getMonthlyInterest());
System.out.println(“This account was created at ” +
account.getDateCreated());
5
}
}
class Account {
private int id;
private double balance;
private static double annualInterestRate;
private java.util.Date dateCreated;
public Account() {
dateCreated = new java.util.Date();
}
public Account(int newId, double newBalance) {
id = newId;
balance = newBalance;
dateCreated = new java.util.Date();
}
public int getId() {
return this.id;
}
public double getBalance() {
return balance;
}
public static double getAnnualInterestRate() {
return annualInterestRate;
}
public void setId(int newId) {
id = newId;
}
public void setBalance(double newBalance) {
balance = newBalance;
}
public
static
void
setAnnualInterestRate(double
newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}
public double getMonthlyInterest() {
return balance * (annualInterestRate / 1200);
}
public java.util.Date getDateCreated() {
return dateCreated;
}
6
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
}
b) (The Fan class) Design a class named Fan to represent a fan. The class contains:








Three constants named SLOW, MEDIUM, and FAST with values 1, 2, and 3 to denote the fan
speed.
A private int data field named speed that specifies the speed of the fan (default SLOW).
A private boolean data field named on that specifies whether the fan is on (default
false).
A private double data field named radius that specifies the radius of the fan (default 5).
A string data field named color that specifies the color of the fan (default blue).
The accessor and mutator methods for all four data fields.
A no-arg constructor that creates a default fan.
A method named toString() that returns a string description for the fan. If the fan is on,
the method returns the fan color, radius, and speed in one combined string. If the fan is not
on, the method returns fan color and radius along with the string “fan is off” in one
combined string.
Draw the UML diagram for the class. Implement the class. Write a test program that creates
two Fan objects. The first should have a speed of SLOW, a radius of 12, a color of orange,
and be initially set to on. The second should have a speed of FAST, a radius of 6, a color of
green, and be initially set to off. Display the objects by invoking their toString method.
Fan
+SLOW = 1
+MEDIUM = 2
+FAST = 3
-speed: int
-on: boolean
-radius: double
-color: String
+Fan()
+getSpeed(): int
+setSpeed(speed: int): void
+isOn(): boolean
+setOn(on: boolean): void
+getRadius(): double
+setRadius(radius: double): void
+getColor(): String
+setColor(color: String): void
+toString(): String
Constant.
Constant.
Constant.
The speed of this fan (default 1).
Indicates whether the fan is on (default false).
The radius of this fan (default 5).
The color of this fan (default blue).
Constructs a fan with default value.
Returns the speed of this fan.
Sets a new speed for this fan.
Returns true if this fan is on.
Sets this fan on to true or false
Returns the radius of this fan.
Sets a new radius for this fan.
Returns the color of this fan.
Sets a new color for this fan.
Returns a string representation for this fan.
public class LabSheet6_3b {
7
public static void main(String[] args) {
Fan1 fan1 = new Fan1();
fan1.setSpeed(Fan1.SLOW);
fan1.setRadius(12);
fan1.setColor(“orange”);
fan1.setOn(true);
System.out.println(fan1.toString());
Fan1 fan2 = new Fan1();
fan2.setSpeed(Fan1.FAST);
fan2.setRadius(6);
fan2.setColor(“green”);
fan2.setOn(false);
System.out.println(fan2.toString());
}
}
class Fan1 {
public static int SLOW = 1;
public static int MEDIUM = 2;
public static int FAST = 3;
private
private
private
private
int speed = SLOW;
boolean on = false;
double radius = 5;
String color = “blue”;
public Fan1() {
}
public int getSpeed() {
return speed;
}
public void setSpeed(int newSpeed) {
speed = newSpeed;
}
public boolean isOn() {
return on;
}
public void setOn(boolean trueFalse) {
this.on = trueFalse;
}
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
radius = newRadius;
}
8
public String getColor() {
return color;
}
public void setColor(String newColor) {
color = newColor;
}
public String toString() {
return “speed ” + speed + “\n” + “color ” + color + “\n”
+ “radius ” + radius + “\n”
+ ((on) ? “fan is on” : “ fan is off”);
}
}
9