OOP2 Manuls 2020 2021
OOP2 Manuls 2020 2021
Lab Manual
Prepared by:
1
Table of Contents
Contents
Table of Contents ............................................................................................... 2
Project#1 (Rectangle) .........................................................................................3
Project#2 (Account) ...........................................................................................4
Project#3 (Student) ...........................................................................................5
Project#4 (Course) .............................................................................................6
Project#5 (CD) ..................................................................................................8
Topic 2: Inheritance and Polymorphism ............................................................... 10
Project#6 (Shape) ............................................................................................ 10
Project#7 (Person) ........................................................................................... 13
Topic 3: Abstract Classes and Interfaces .............................................................. 14
Project#8 (Colorable – abstract class) ................................................................. 14
Project#9 (Colorable - interface)......................................................................... 15
Project#10 (Animal - Implementing Class Diagram) ............................................. 166
Sample Exam .................................................................................................. 16
Topic 4: Graphical User Interface GUI .................................................................. 21
Project#11 (Components).................................................................................. 21
Project#12a (FlowLayout).................................................................................. 22
Project#12b (GridLayout) .................................................................................. 22
Project#12c (BorderLayout) .............................................................................. 22
Project#13 (Microwave) .................................................................................... 23
Project#14 (Event Handling) .............................................................................. 24
Project#15 (Dollars) ......................................................................................... 25
Project#16 ...................................................................................................... 26
Project#17 ...................................................................................................... 26
Appendices...................................................................................................... 28
Appendix A: Course Syllabus .............................................................................. 28
Appendix B: Graphical User Interface (General Notes) ............................................ 30
Appendix C: General Notes on GUI ...................................................................... 31
Appendix D: GUI Classes Hierarchy ..................................................................... 32
Appendix E: Event Handling ............................................................................... 33
Appendix F: Read and Write in Java .................................................................... 34
2
Topic 1: Classes and Objects
Project#1 (Rectangle)
Create a project named Proj1, In Proj1 class create class named Rectangle. In the
Rectangle class:
1) Declare 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.
2) Declare a string data field named color that specifies the color of a rectangle.
Assume that all rectangles have the same color. The default color is
white.
5) Define get and set methods for all the width and height data fields. For
the width and height setters, check that the new values are non-negative.
6) Define a method named getArea() that calculates returns the rectangle area
(Hint: area=width*height).
7) Define a method named getPerimeter() that calculates and returns the rectangle
perimeter. (Hint: perimeter=2*width+2*height)
3
Project#2 (Account)
1) Create Java project named project2. In the project2 create class named Account. In the Account
class do the following:
a) Declare an integer data field named id (default value= 0)
b) Declare a double data field named balance (default value= 0.0)
c) Declare a double data field named annualInterestRate (default value=0.0).
The annualInterest Rate is fixed for all accounts.
d) Declare a Date data field named name dateCreated that contains the date when the
account was created.(Hint :- use the following package java.util.Date)
e) Define a no-argument constructor that creates a default account.
f) Define the accessor and mutator methods for id, balance, and annualInterestRate.
g) Define the accessor method for the dateCreated.
h) Define a method named withdraw (double) that withdraws a specified amount
from the account.
i) Define a method named deposit (double) that deposits a specified amount to the account.
j)
2) In the main() method do the following:
a) Create an account object (acc1) with (ID=1122, balance=1000, and annualInterestRate=5.5%)
b) Deposit 30, 40, and 50 to the account.
c) Withdraw 5, 4, and 2 from the account.
d) Print an account summary that shows account ID, annualInterestRate, balance, and the
date when the account was created.
4
Project#3 (Student)
d. Create a default constructor, each time a student is created the count variable is
incremented by 1, and is given an ID that equals to the value of count at that
moment . [Hint:- read the name of student from user]
5
Project#4 (Course)
Create a Java project named Proj4. In Proj4 create a class named Course as follows:
Attributes:
name: name of the Course.
instructorName: name of the instructor of the course.
6
Main:
public static void main(String[] args) {
c.addStudent(1111, 95);
c.addStudent(1111, 95);
c.addStudent(2222, 85);
c.addStudent(3333, 75);
c.addStudent(4444, 65);
c.addStudent(5555, 55);
7
Composition
Project#5 (CD)
Suppose you are working with audio CDs, where each CD has a title, an artist name, and a number of
tracks with different lengths.
8
11. In the Java main class, do the following:
a. Create a CD object named mycd with a title "Quran", artist name: "Affasi",
number of tracks 3.
b. Create three tracks:
t1: (“doha”, 3 min, 20 sec)
t2: ("zalzala", 4 min, 15 sec)
t3: ("nas",1 min, 2 sec)
c. Add the three tracks t1, t2, t3 to the cd named mycd.
d. Print the total length of the CD. ( Hint use printTotalTime() method )
9
Topic 2: Inheritance and Polymorphism
Project#6 (Shape)
10
f. Define the method getArea() that calculates and returns the area of
a triangle (area=0.5*base*height).
14. Create a class named Circle that extends the Shape class, in the Circle class do the following:
a. Declare a private double data field named radius. “The default value radius=1.0”.
b. Create a no-argument constructor that sets radius for its default value.
c. Define the method setRadius(double) that sets the radius to the given value if it
is nonnegative, and to 0.0 otherwise.
d. Create a one-argument constructor that sets the radius to the given value. “Hint:
use the previously defined setRadius method”.
e. Create a two-arguments constructor that sets the radius and the color to the
given values. “Hint: use the previously created one-argument constructor”.
f. Define the method getRadius() that returns the radius of a circle.
g. Define the method getDiameter() that returns the daiameter of a circle.
“Hint: diameter= 2*radius”.
h. Override the method describe() in the Shape class to print Shape description
then the statement “This is a Circle”.
i. Override the method getArea() in the Shape class to calculate the area of a circle.
“Hint: area=PI*radius*radius”.
15. In the main method do the following:
a. Create a default Shape named s1, then print its color, description, and area.
b. Create a default triangle named t1, then print its color, description, and area.
c. Create a triangle t2 with (height=5, base=9, and color=”blue”).
d. Create a default circle named c1, then print its color, description,
radius, diameter, and area.
e. Create a default circle named c2, then print its color, description,
radius, diameter, and area.
f. Create Circle object named p and assign its reference to a variable of type shape.
g. Call describe() method using object p.
h. Try to print the diameter of object p using the getDiameter() method.
16. In the same project create a package named proj6_B. In this package, create a class
named Cylinder that extends Circle class. In the Cylinder class do the following:
a. Declare a private double data field named “height”, “default value is height=1.0”.
b. Create a no-argument constructor that sets height to its default value.
c. Create a two-arguments constructor that sets the height, radius to its given values.
d. Create a three-argument constructor that sets the height, radius, and color to
its given values. “Hint: use the previously created two-arguments constructor”.
e. Define the method setHeight(double) that sets the value of the height data field.
f. Define the method getHeight() that returns the value of the height data field.
g. Define the method getVolume() that calculates and returns the volume of a cylinder.
“Hint: volume=height* circle_area”.
11
17. In the main method do the following:
a. Create a default cylinder cy1, then print its height, base radius, base area,
and volume.
b. Create a cylinder cy2 with heigh=5.0, radius=2.0, and color=”pink”, then
print its height, base radius, base area, and volume.
12
Project#7 (Person)
13
Topic 3: Abstract Classes and Interfaces
Project#8 (Colorable – abstract class)
14
Project#9 (Colorable - interface)
getArea(), which returns a
double
howTo Color(), which returns a
string
2. Create a class named Circle that implements the Colorable interfce.
Circle class has an Integer data field named radius.
4.For Circle objects, the getArea() method calculates and returns the area of the circle
according to the formula (c_area= PI* radius^2).
5.For Rectangle objects, the getArea() method calculates and returns the area of the
rectangle according to the formula (r_area= width*height)
6.For Circle objects, the howToColor() method returns a String that colors the Circle according to its
area “Hint: using the getArea() method”. If the area of the circle is greater than 50, the return color
will be “Red”, else the color will be “Yellow”.
7.For Rectangle objects, the howToColor() method returns a String that colors the rectangle
according to the width the rectangle. If the width is greater than 50, the returned color will be
“Black”, else the color will be “White”.
Create a Rectangle object with a width and a height specified by the user.
Fill the array with the created objects.
Write a suitable call to the method printObjects(Colorable []) to
print information about the create objects.
15
Project#10 (Animal - Implementing Class Diagram)
Examine the following Class Diagram, then answer the following questions:
9. Create a Java project named Proj 10, and convert the above class diagram into
Java code. Methods behaviors are illustrated below:
a. Drink(): displays “drink water”
b. Move() [in Mammals] returns “Walk”
c. Move() [in Birds] returns “fly”
d. makeNoise() [in Finch] returns “beep”
e. makeNoise() [in Horse] returns “neigh”
f. descFuel() [in Horse] prints “No Fuel”
g. getType() [in Horse] returns “Horse”. “Hint: use the getClass() method”
h. beFriendly() [in Horse] prints “can live with humans”
10. Create a Java main class named Test, in the main() method do the following:
a. Create a Horse object named h1, and set its food to “oats”.
b. For this object display its: food, friendship, type, fuel, drink, noise, and move.
c. Create a Finch object named F1, and set its food to “seeds”.
d. For this object display its: food, drink, noise, and move.
16
Sample Exam
Hashemite University
Prince Al-Hussein bin Abdullah II Faculty
for Information Technology
Department of Computer Science
Course ID 151001212
Academic Year 2018/2019
Semester
Exam
Second Semester
Mid Exam 40
Date 14-3-2019
Time 9-11 AM
Student ID
Instructor Name
Section ID
PC NO
Q1 /40
17
Create Folder with your ID on the Desktop.
Q1- Within your ID Folder Create java project named Question1,
examine UML Diagram below and do the Following steps in Question 1.
A).Create inteface named PriceAdmin. The PriceAdmin contains the following methods.
1. Public double calcualtePrice() .
B).Create interface Named VehcileAdmin. The VehcileAdmin contain the following methods
1. Public void DescribeCar().
E).Create package Named q1_b, within this package create class named Seat and do the following
1. Create empty default constructor.
18
18
F).Create class Named vehicle that implements PriceAdmin interface and Vehcile
Admin interface. In Class Vehcile
do the following:-
1. Declare protected wheel array named warr[4] with size four.
2. Declare protected seat array named sarr[5] with size five.
3. Declare engine object named e.
4. Create default constructor . Hint within default constructor using loops complete the deceleration of war[]
array and sarr[] array to represent actual object arrays.
5. Override to String method to return the name of the class.
F).Create class Named car that extends the vehcile class. In Class Car
do the following:-
1. Declare protected integer named carcount with default value zero .Hint each time the car is created
carcount must be incremented by one.
2. Declare protected String array named manfuctrurename filled with the following list
{"Toyota","Nissan","Honda","Hondai"} . Note the list of manfuctrurename array is unified for all cars .
3. Create default constructor.
4. Override toString() method . toString() method must return the String returned from toString() in
the super class concatenated with “2019” . Hint :- invoke toString() in the superclass.
F).Create class Named vancar that extends car. In Class vancar do the following:-
1. Override calculatePrice() to return the price of car. The base price of all cvanars is 35000 JD.
If the powerenginee of car is less than or equal 1500 JD the tax will be 14% and 1000 JD will be added to the
total price.
If the powerenginee of car is equal 2000 the tax will be 16% and 1500 JD will be added to the total price.
Otherwise the tax will be 18% and 2000 JD will be added to the total price.
2. Override DescribeCar() method to print the calculated price of car .
3. Overload equals(vancar r) method. equals method will return true if the vancars have the sameprice and r
is instanceof vancar, otherwise will return false.
F).Create class Named Sportcar that extends car class. In Class Car do the following:-
1. Declare private integer data field named modelyear.
2. Declare private integer data field named modelnumber.
3. create default constructor.
4. create one argument constructor that takes specified model modelyear.
5. create two arguments constructor that takes specified model modelyear and specified model number.
Hint :- use previous created constructor.
6. Override calculatePrice() to return the price of car. The base price of all sport cars is 2000 JD and the tax is 20%.
7. Override DescribeCar() method to print the modelnumber and modelyear of car.
8. Override equals(Object) method. Equals will return true if sportcars have the same value of powerengine.
Otherwise the method will return false.
19
8. Define method within main class named searchmodel(String m ), the search method is looking for within the
manfuctrurename array that has been declared within car class. if the m string has been foundwithin array
the index of element will be returned otherwise -1 will be returned . Hint:- use equalIgnoreCase() method.
9. Invoke search method to look for “Honda”.
10. Print the final number of cars.
Good Luck
20
Topic 4: Graphical User Interface GUI
Hint: See Appendix C
Project#11 (Components)
Create the following GUI. You do not have to provide any functionality. (Hint: use the flow layout)
21
Project#12a (FlowLayout)
Project#12b (GridLayout)
Project#12c (BorderLayout)
22
Project#13 (Microwave)
Create the following GUI for the front of a microwave oven. You do not have to provide any
functionality.
23
Topic 5: Event Handling
Create the following GUI. When the user enters a text in the textfield and click on the button "Show
on text area", the text is displayed on the text area. When the user clicks on "Show on message
box" the text is displayed on a message box.
24
Project#15 (Dollars)
Write a program that converts US dollars into Canadian dollars, as shown in the following figure.
The program let the user enter an amount in US dollars and display it equivalent value in Canadian
dollars when clicking the Convert button. One dollar is 1.5 Canadian dollars.
Home Work :- add another Button at the center of bottom panel Named Clear. Clear Button clears the
text fields and prepare the Converter system to new operation.
25
Project 16
Design the GUI illustrated in the figures and Follow the guidelines below to make the GUI interactive .
Hints :-
The bee.png and Flowers.png have been copied on the desktop .
The background color of JButtons , JRadioButtons : PINK .
Border Style: Titled Border, Line border .
Include The Radio buttons within one ButtonGroup .
Size of GUI 600,600.
Copy the bee.png and flower.png to your folder that contain your solution.
Label L1
Color : PINK
Label L2
Color: YELLOW
Label L3 :
Flowers.png
26
Guidelines :-
Change Font Button :-Sets the font L1 to be : Calibari", BOLD and ITALIC ,16 .
Exit : Exits the application, also when the user presses the keyboard key E.
Clear Selection : Clears the selection of radio buttons and ComboBox.
Left Radio Button:- Sets the left alignment : [Text within L1 and Image within L2].
Center Radio Button:- Sets the center alignment : [Text within L1 and Image within L2].
Right Radio Button:- Sets the right alignment : [Text within L1 and Image within L2].
Set line Border (ComboBox) :- Sets the line border(color : black , thickness : 5) for L2
Set Titled Border :- Sets Titled Border (bee image ) for L2.
Set suitable toolTipText for exit, change font, Exit and Clear selection buttons.
27
Project 17 (Files)
Design the GUI illustrated in the figures and Follow the guidelines below to make the GUI
interactive.
Import Button : - Read File (Saved within your Project) line by line and import it in the TextArea.
Export Button:- Export the text within TextArea into text file (text file will be saved
within your folder)
28
Project 18 : Error Handling Simple example
Write the following codes within Java environment and study the
outputs of the code.
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
29
Appendices Appendix A: Course Syllabus
Hashemite University
Course Syllabus
Credit Hours
Course No. Course Title Designation Prerequisite Co-requisite
Lectures /Lab.
Object Oriented
191001213 Programming 2 Required - 151001212 1/0
Lab
a) Textbook(s):
th
1. Introduction to JAVA programming – Comprehensive Version, Y. Daniel Liang, 8
edition, Pearson Education, 2010
b) References:
1. www.java.sun.com
28
30
th
2. Deitel & Deitel, Java: How to Program, 9 edition , Prentice Hall, 2011.
Course
No. of Contact
Topic Details ILO Reference
Weeks hours*
number
1. Objects and Classes 1 Ch8 3 9
2. Inheritance and Polymorphism 1 Ch11 4 12
3. Abstract Classes and Interfaces 1 Ch14 2 6
4. GUI Basics 2 Ch12 2 6
5. Event-Driven Programming 3 Ch16 2 6
6. Exception Handling 4 Ch13 1 3
Total 14 42
31
Appendix B: Graphical User Interface (General Notes)
In order to create a Java GUI, you have to follow the following guidelines:
32
Appendix C: General Notes on GUI
In order to create a Java GUI, you have to follow the following guidelines:
33
Appendix D: GUI Classes Hierarchy
34
Appendix E: Event Handling
35
Appendix F: Read and Write in Java
import java.io.*;
class FileRead
try{
String strLine;
in.close();
36
import java.io.*;
class FileWrite
// Create file
out.append("Hello to Java");
out.close();
37