Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

ADDIS ABABA UNIVERSITY

ADDIS ABABA INSTITUTE OF TECHNOLOGY


School of Electrical and Computer Engineering

Object Oriented Programming (ECEG-3162)


Laboratory Manual (Version 2.0)

Compiled By: Hailemelekot D.


September, 2015GC.
Addis Ababa, Ethiopia
Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #1
(Compiling and Running Simple Java Programs)

Objective
• Compiling and Running Simple Java Program From Windows Command Prompt(CMD) or Linux Terminal

Preparation Tasks
• No preliminary preparation required for this laboratory session

Activities
a. Procedures
→ Create a folder on your preferred directory to store the work you will do in this class. The name of
the folder should have no spaces.
→ Open note pad and type the following Java code
public class HelloWorld
{
public static void main( String[ ] args)
{
System.out.println(“Hello, World!”);
}
}
→ Save the file asHelloWorld.javain thedirectory which you created in the previous step.
→ Open Windows CMD/Linux Terminal and change your current directory to the one which you saved
the above Java code. To change the current directory to any directory you can use CD command.
→ Compile the source code you wrote in Step 2 by now typing the following command at the prompt
and pressing enter: javac HelloWorld.java 1
→ Now run your program by executing the following command at the command prompt: java HelloWorld
b. Now change the HelloWorld code so that it prints out Goodbye, World!.
c. The command System.out.println prints out its argument and then starts a new line. Change your program
so it prints out Hello, World! on one line and then prints outGoodbye, World! on the next line.
d. Add these lines to yourmainmethod and compile the code and run it:
String name = “Ethiopia”;
System.out.print(“Hello,”);
System.out.println(name);
System.out.println(“How are you today?”);
e. Without doing any programming, what do you think the following main method prints to the screen?
public static void main(String[ ] args) {
int x = 5;
int y = 3;
int z = x + x * y - y;
System.out.println( ”The value of z is ” + z );
1 Note: javac stands for Java Compiler. If running this command prints any errors to the command prompt window, then you

either did not write the Java code correctly or you did not give the Java file the right name. Make sure each is copied precisely,
character by character, with correct capitalization, and then try to recompile. If it compiles successfully, it will print out nothing and
simply show the next prompt.You can verify that your program successfully compiled by listing the contents of the directory using the
command dir. You should see the file that you wrote in Notepad, HelloWorld.java, and a second file, the bytecode produced by the
Java compiler,HelloWorld.class.

May 13, 2017 Compiled by: Hailemelekot D. Page 2


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

int w = ++x + y + y−−;


System.out.println( “The value of w is ” + w );
System.out.println( “The value of x is now” + x );
System.out.println( “The value of y is now ” + y );
boolean a = true;
boolean b = false;
boolean c = (( a && ( !( x > y ))) && (aky > x));
System.out.println( “c is ”+ c );
}

f. Create a new Java file with a class called UsingOperators and copy the above main method into it.
g. Create a new Java class calledTempConverter. Add a main method to TempConverterthat declares and
initializes a variable to store the temperature in Celsius. In the main method, compute the temperature in
Fahrenheit according to the following formula and print it to the screen:
9
F ahrenheit = × Celsius + 32
5

h. Create a new class called UsingControlStructures


→Add a main method to the class, and in the main method declare and initialize a variable to represent
a person’s age.
→ In the main method, write an if-else construct to print out “You are old enough to drive” if the
person is old enough to drive and “You are not old enough to drive” if the person is too young.

i. Write a for loop and a while loop that prints out all the odd numbers from 100 to 0 in decreasing order.
j. Create a new class called Gradebook
→ Add a main method to Gradebook. In the main method, declare and initialize an array of doubles to
store the grades of a student.
→ Write a loop to print out all the grades in the array. Make sure that your printout is readable with
spaces or new lines between each grade.
→ Write a new loop to find the sum of all the grades in the array.
→ Divide the sum by the number of grades in the array to find the student’s average.
→ Print a message to the user showing the average grade. If the average grade is 99.9, the output should
be “Your average grade is 99.9”
→The program shall be versatile and shall have the capacity to work for any number of grades that the
user enters.
→ Your program should work if there are 4 grades in the array or 400 grades in the array. That is, you
should be able to change the number of grades in the initialized array and compile, and it should run without
any problems. Try it out. If it does not, figure out how to rewrite your program so that it does work.
→Add code to print out the letter grade the student earned based on the average grade. An average in
the 90’s is an A, in the 80’s a B, the 70’s a C, the 60’s a D, and anything lower is an F.
k. Write a Java program that computes the sum and product of two matrices. The size of the matrices shall be
determined by the user of the program.

l. Write a Java program that prints all prime numbers which are less than any number n. The number n shall
be determined by the user.

May 13, 2017 Compiled by: Hailemelekot D. Page 3


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #2
(Programing Using JAVA Methods)

Objective
• Enabling students to develop modularize code using Java methods.
• Introducing method overloading(Compile time polymorphism).

Preparation Tasks
• No preliminary preparation is not required for this laboratory session

Activities
a. Grade Book program: Continued from the previous lab.
→ Add a method to Gradebook called printGrades that accepts an array of doubles as an argument and
prints out all the grades in the array. Replace the loop in the main method that prints out all the grades
with a class toprintGradesmethod.
→ Add a method to Gradebook called averageGrade that takes an array of doubles as an argument and
returns the average grade. Replace the loop and calculations in the main method that determines the average
grade with a call to the averageGrade method. Your main method should still print out the user’s average
grade and the letter grade the user earned.
→ Change the main method of Gradebook so that it converts its String arguments into doubles and
initializes the grades in the array to those numbers. Use the method Double.parseDouble to convert a String
containing a double to an actual double. Compile and run and provide arguments at the command line like
this:

java Gradebook 82.4 72.5 90 96.8 86.1

→Try to modify your code so that instead of just taking the array of grades from the main method, the
program asks the user to enter the grades.
→Change the main method so that after asking the user to enter the grades, it prints out a menu of two
options for them.
1: Print out all the grades
2: Find the average grade
→It should ask the user to enter the number of his choice and do what the user chooses. (Note: This
feature is required to be implemented using switch statements)
b. Create a class called MethodsOverloading and create the following methods inside the class:
→calcArea...return type...doubleparameters: double [to calculate the area of circle]
→calcArea...return type...double...parameters: double, double [to calculate the area of rectangle]
→calcArea...return type...doubleparameters: double, double, double [to calculate the area of trapezium]
→calcArea...return type...double...parameters: int ,int to [to calculate the area of a triangle ]
→Finally include a main method to your class and test all the methods that you created before by
passing appropriate data as an argument.
c. Write a Java program that that calculates the value of ex from its Taylor series expansion as shown below:
x x2 x3 x4 x5
ex = 1 + + + + + + ...
1! 2! 3! 4! 5!
- The program shall be organized using methods and the size of the series and the value of x shall be
determined by the user. In addition, the program shall have a method to check the accuracy of the result for
a certain size of a series selected by the user given that the value of e=2.71828182846

May 13, 2017 Compiled by: Hailemelekot D. Page 4


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

d. Write a Java method called sortArray which is intended to perform sorting of a given array. The size of the
array and the elements of the array shall be determined by the user of the program. Taking of the appropriate
data from the user shall be implemented using a method named readArray that take an array of double and
integer as argument.

e. Write a Java program that calculates the Fibonacci series up to a given number n which is determined by
the user. The program shall be implemented using recursive and non-recursive Java methods.
f. ROCK, PAPER AND SCISSORS GAME
Write a program that lets the user play the game of Rock, Paper, Scissors, against the computer. The
program should work as follows.
→ When the program begins, a random number in the range of 1 through 3 is generated. If the number
is 1, then the computer has chosen rock. If the number is 2, then the computer has chosen paper. If the
number is 3, then the computer has chosen scissors. (Don’t display the computer’s choice yet.)
→The user enters his or her choice of “rock”, “paper”, or “scissors” at the keyboard. (You can use a
menu if you prefer.)
→The computer’s choice is displayed.
A winner is selected according to the following rules:
→If one player chooses rock and the other player chooses scissors, then rock wins, (The rock smashes
the scissors.)
→If one player chooses scissors and the other player chooses paper, then scissors wins (Scissors cuts
paper.)
→If one player chooses paper and the other player chooses rock, then paper wins. (Paper wraps rock.)
→If both players make the same choice, the game must be played again to determine the winner.

Be sure to divide the program into methods that perform each major task.

g. ESP GAME
Write a program that tests your ESP (extrasensory- perception!) The program should randomly select the
name of a color from the following list of words:

Red, Green, Blue, Orange, Yellow

To select a word, the program can generate a random number. For example, if the number is 0, the selected
word is Red; if the number is l the selected word is Green; and so forth. Next, the program should ask
the user to enter the color that the computer has selected. After the user has entered his or her guess, the
program should display the name of the randomly selected color. The program should repeat this 10 times
and then display the number of times the user correctly guessed the selected color.

Be sure to modularize the program into methods that perform each major task.

May 13, 2017 Compiled by: Hailemelekot D. Page 5


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #3
(Java Object Oriented Programming Concepts I: Introduction To Classes and Objects)

Objective
• Enabling students to create deep understanding about Java classes and objects through practical programing
Exercises

Preparation Tasks
• Revising/understanding the theoretical concepts which are dealt in the lecture class.

Activities
a. Grade Book Program: Continued from the Previous laboratory exercises (OOP implementa-
tion)
→ Create a new class called GradebookOO. The class should have a single field which is an array of
doubles called grades. This class will have no main method. Compile. Why can’t you run this class?
→ Write two constructors for GradebookOO. The first should take no arguments and initialize the grades
field to an array of size zero. The second should take an argument that is an array of doubles and assign that
array to the field. Compile.
→ Add a method to GradebookOO named printGrades that takes no arguments and prints out all the
grades in the grades field. Compile.
→ Add a method to GradebookOO named averageGrade that takes no arguments and returns the average
grade in the grades field. Compile.
→ Create a new class called GBProgram. Add a main method to GBProgram which instantiates a
Gradebook with an array of grades, prints out all the grades with a call to the printGrades method, and finds
the average grade with the averageGrade method. Compile and run.
→ Print out a menu to the user, as described in the previous lab session that allows the user to select
whether they would like to print out all the grades or find the average grade.
b. Grade Book Program: Continued from the Previous laboratory exercises (OOP implementa-
tion) . . .
→Add appropriate access modifiers to all your fields and methods in GradebookOO and GBProgram.
Compile.
→ Add a method to GradebookOO called addGrade which accepts a double argument and adds it to
the array of grades.
→Delete the GradebookOO constructor that takes an array of doubles as an argument. And change the
main method of GBProgram so that it instantiates an empty GradebookOO and adds the grades one-by-one
to it with the addGrade method.
→Add a method deleteGrade to GradebookOO which accepts a grade as an argument and removes it
from the array if it is there.

c. Grade Book Program: Continued from the Previous laboratory exercises (OOP implementa-
tion) . . .
→ Change the field in the GradebookOO program from an aray to an ArrayList.
→Rewrite all the methods to use the ArrayList instead of the array. Make sure you use an Iterator for
all the iterations through the ArrayList.

Do you have to make any changes to GBProgram so that it will compile and run successfully? Why or
why not?

May 13, 2017 Compiled by: Hailemelekot D. Page 6


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

d. Develop a Java class called Point based on the following details.


→ The class shall have two public fields [which are declared as a double and has a final modifier]
→ One public field as double data type and static and final modifier [to hold the mathematical value of
pi]
→ One default constructor which initializes the two fields of the class
→ One parametrized constructor that initializes the two fields of the class
→ The class shall comprise a methods to access the fields of the class;
→ The class should also comprise a method that takes Point object as an argument and returns the
distance between the original point and the point object which passed as an argument to the point.
→ It also comprise a method that calculates the volume of sphere that is generated by revolving an
object P to the origin.
→ Finally create another class called PointTest that comprise a main method which is intended to
instantiate the class point and test the result by passing the appropriate argument to the methods and
constructors of the class.

e. Design a Java class called complexNumberOperation which is intended to perform all operations
of complex number. The class shall have the following features:
- Two private attributes: realPart and imaginaryPart both as a double data type
- One public attribute: objectCreationCount which is static and int data type
- Two constructors: The one with two parameters as a double and the other with no parameters.
The class shall also comprise the following methods(As per they are are shown in the following table.):

Function Parameters Return Type


addComplex Two complexNumberOperation objects Complex number object
subComplex Two complexNumberOperation Complex number object
mulComplex Two complexNumberOperation objects Complex number object
divComplex Two complexNumberOperation objects Complex number object
modComplex One complexNumberOperation object double
setReal double void
getReal - double
setImaginary double void
getImaginary - double

All the constructors and methods shall be implemented well to perform the intended functionality. In addition
the third public attributes are used to count how many objects of (instances) are created form the class.
All the constructors and methods shall be implemented well to perform the intended functionality. In addi-
tion the third public attribute is used to count how many objects of (instances of) complexNumberOperation
are created. After completing the implementation of the class create another class called complexNumber-
OperationTest in your current package and write a Java code to define a main method inside the class. Then
implement all necessary functionality to test you previous class.

And finally test your class by creating instance of a class using default constructor, parameterized con-
structor, and by using the get and set methods. All the above steps shall be done in one step and your
program shall have a mechanism to report how many objects of (instances) complexNumberOperation class
are created.

May 13, 2017 Compiled by: Hailemelekot D. Page 7


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #4
(Java Object Oriented Concepts (Static and Final Modifiers and Inheritance concepts))

Objective
• Understanding the static and final modifiers through practical programming exercises.

• Writing reusable code by applying the concepts of inheritance.

Preparation Tasks
• Revising/understanding the theoretical concepts which are dealt in the lecture session.

Activities
a. Racecar Class OOP implementation
→Create a new class called Racecar. Add two fields to Racecar: a field of type String to store the name
of the car and a field of type Color (from Java.awt.Color) to store the color of the car. Each car can have a
different name and color. Should the fields be static or non-static?
→ Every one of our racecars will have the same top speed. Add a private constant of type double to the
Racecar class to store the top speed and initialize it to any number you want. Should this field be static or
non-static?
→ Add a constructor to Racecar which accepts a name and color argument and assigns the arguments
to the name and color fields of the class.
→ Add a method called getName that returns the name of the car and a method called getColor that
returns the color of the car. Should these methods be static or non-static?
→ Add a method to Racecar called race which accepts two Racecars as arguments, simulates a race
between the two, and returns the car that wins the race, or null if the race is a tie. The method should
calculate a random speed for each car between 0 and the top speed. The car with the higher speed wins
the race, but if they both have the same speed they tie. The method random in Java.lang.Math returns a
random double between 0 and 1. If you multiply this random number by the top speed, the product will be
a random number between 0 and the top speed. Should this method be static or non-static?
→ Add a main method to Racecar which creates two Racecars, races them against one another, and
prints out the winner’s name. When instantiating the Racecar objects, pass one of the static fields of the
Color class (like RED or BLUE) as the color argument to the constructor. Should the main method be static
or non-static?
→ Instead of having a constant top speed for all racecars, change the Racecar class so every car has its
own top speed.

b. Students Class OOP Implementation for demonstrating the Concept of inheritance


→ Create a package called students. All the classes you create in this will be created in this package.
→ Create a class called Student, which should have two properties, a name and a year and methods
to get the name and get the year of the student. Initialize these properties to arguments passed into the
constructor.
→ Create a subclass of Student called Undergrad. The Undergrad constructor should accept name and
year arguments. Add a method to Undergrad called description which returns a String containing the name
of the undergrad, then a space, then a capital ’U’, then a space, and then the year of the undergrad. For
example, the description method of an Undergrad instance with the name ”Michael” and the year 2006,
should return the String “Michael U 2006”.
→ Create a subclass of Student called Grad. The Grad constructor should accept only the name of the
Grad as an argument, and it should always initialize the Grad’s year to 5. Add a description method to Grad

May 13, 2017 Compiled by: Hailemelekot D. Page 8


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

which returns a String containing the name of the Grad, followed by a space and then the letter ’G’. The
description method of a Grad named
Jennifer should return the String sayJennifer G.
→ Create a subclass of Undergrad called Intern. In addition to the name and year properties, Intern
should have a wage and a number of hours that are initialized in the constructor. Add a getPay method to
Intern which returns the wage times the number of hours. Add a description method to Intern which returns
a String containing the result of calling Undergrad’s description method followed by the return value of the
getPay method. The description method of an Undergrad named Elizabeth” whose year is 2005 and worked
20 hours at $10.32/hour, should return the String “Elizabeth U 2005 206.4”.
→ Create a subclass of Grad called ResearchAssistant. ResearchAssistant has a salary that is initialized in
the constructor and a getPay method that returns the salary. Add a description method to ResearchAssistant
which returns a String containing the result of Grad’s description method, followed by the result of getPay.
The description method of a ResearchAssistant with the name “Greg” and a $2000.00 salary would return
the String “Greg G 2000.0”.
→ Create a class called StudentTest that has a main method. Use the main method to test the class
hierarchy you just built. Create some instances of Undergrad, Grad, Intern, and Research Assistant. Print
out the result of their description methods. Compile and run.

May 13, 2017 Compiled by: Hailemelekot D. Page 9


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #5
(Java Object Oriented Concepts (Abstract Data Types))

Objective
• Understanding the concept of abstract data types through practical Java object oriented programming exer-
cise.

Preparation Tasks
• Revising the basic Java programming elements and the concepts of classes and objects .

Activities
a. Implementing Simple Counter Program for Demonstrating Abstract Data Types(ADT)
- Create a Java package called ADT
- In this package create a class named ADTCounter which have the following members:
1. One private field of type int named countValue
2. One default constructor that initializes the private field of the class to zero
3. Four public methods accessing the current value stored in the field of the class, for incrementing
the current value stored in the class by one, decrementing the current value stored in the class by one and
resetting the value of the field to the default (Starting) value.
4. The implementation shall be user friendly and handle all erroneous results which can be at runtime
of the program.
5. Finally create another class called ADTCounterTest class in the same package and create a main
method inside this class. Instantiate your previous class (ADTCounter) in the main method test the all the
expected functionality of your program by feeding hypothetical data and/or calling appropriate method in
the class.
b. Implementing Fraction Class for Demonstrating Abstract Data Types(ADT)

Within the ADT package create a class named Fraction which is intended implement all features and vi-
sual representation of a real number system in fraction form. The class shall have the following members:
→ Two private fields
numerator. . .int
denominator. . .int
→ Two constructors:
One Default constructor that initializes the numerator to 0 and denominator to 1
One parametrized constructor that initialized the private fields of a class based on the argument
passed during class instantiation. 2
→ Appropriate accessor(getters) and setter methods for all private fields of the class.
→ The following public methods to perform the respective functionalities described in front of each
method.
formString. . .which is intended to represent a fraction as a string in the form of “numerator/denominator”
→ simplify. . .takes fraction object as a parameter and converts to its simplest form provided that
the fraction can be simplified( 10 5
26 shall be converted to 13 ) but if the fraction cannot be simplified it returns
the original fraction.
2 Note: In this case, the appropriate error handling mechanism shall be applied during initialization. For instance, if the user enters

1 as numerator and 0 as denominator the program shall prompt appropriate error message and shall automatically exit.

May 13, 2017 Compiled by: Hailemelekot D. Page 10


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

→ The class shall also include methods to perform the four arithmetic operations on fraction. These
functions shall take two fraction objects as an argument and returns the result as a fraction object
→The class shall also have a method to check the equality of two fractions. This function shall take two
fraction object as an argument and returns true if they are equal and false if the are not equal.

Note: The details of the methods in the class is presented in the following table.

Function Parameters Return Type


formString int numerator, int denominator String
setNumirator int numirator void
getNumirator - int
setDenominator int void
getDenominator - int
simplify One Fraction Object Fraction Object
addFraction Two Fraction Objects Fraction Object
subFraction Two Fraction Objects Fraction Object
mulFraction Two Fraction Objects Fraction Object
divFraction Two Fraction Objects Fraction Object
areEqual Two Fraction Objects boolean

May 13, 2017 Compiled by: Hailemelekot D. Page 11


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #6
(Abstract Classes, Interfaces and Polymorphism Part I)

Objective
• Demonstrating the concepts of abstract classes, interfaces and polymorphism.

Preparation Tasks
• Understanding/Revising the object oriented concepts that are covered in the previous laboratory sessions.

Activities
a. Based on the following UML diagram and instructions given at the bottom develop a simple
Java program.

→ Create the Animal class, which is the abstract superclass of all animals.
Declare a protected integer attribute called legs, which records the number of legs for this animal.
Define a protected constructor that initializes legs attribute.
Declare an abstract method eat.
Declare a concrete method walk that prints out something about how the animals walks. This methods
shall include legs attribute while describing animals walking mechanism.

May 13, 2017 Compiled by: Hailemelekot D. Page 12


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

→ Create the Spider class.


The Spider class extends the Animal class.
Define a default constructor that calls the superclass constructor to specify that all spiders have eight
legs.
Implement the eat method.
→Create the Pet interface as per the UML diagram shown above.
→Create the Cat class that extends Animal and implements Pet.
This class must include a String attribute to store the name of the pet.
Define a constructor that takes one String parameter that specifies the cat’s name. This constructor
must also call the superclass constructor to specify that all cats have four legs.
Define another constructor that takes no parameters. Have this constructor call the previous construc-
tor (using this keyword) and pass an empty string as the argument.
Implement the Pet interface methods.
Implement the eat method.
→Create the Fish class. Override the Animal methods to specify that fish can’t walk and don’t have
legs.
→Create a class named AnimalClassTest, add a main method and manipulate instances of the
classes that are created before by starting with:
Fish d = new Fish();
Cat c = new Cat(“Fluffy”);
Animal a = new Fish();
Animal e = new ();
Pet p = new Cat();
→After instantiating the above classes in the main method, you shall experiment:
By calling the methods in each object
By casting objects.

May 13, 2017 Compiled by: Hailemelekot D. Page 13


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming (ECEG-3162)
Laboratory Exercises #7
(Realizing the Concept of polymorphism Using Class Hierarchy )

Objective
• Understanding the Concept of polymorphism using class hierarchy.

• Understanding the basics of UML class diagrams which ease the object oriented analysis and design tasks.

Preparation Tasks
• Understanding/Revising the object oriented concepts that are covered in the previous laboratory sessions.

Activities
a. Using the following UML class diagram and the companion instructions given below, develop
a fully functional Java program that demonstrate runtime polymorphism
-Create an abstract class named Employee which is a parent class.

May 13, 2017 Compiled by: Hailemelekot D. Page 14


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

→The class shall comprise three private fields of String: firstName, lastName, socialSecurityNum-
ber and a total of five public methods: one abstract method named calculateEarnings that take no param-
eters and returns double, other three public methods that take no parameter and returns the three private
fields of the class. And one method named toString which takes no parameter and returns string. This
method is intended to override the method named toString() which is found in Java.lang.object class.
→Create a class SalariedEmployee which is a sub class of employee and has one private attribute of
double data type named weeklySalary. The class shall also comprise public methods for initializing and
accessing its private field. The class shall also comprise two methods that override the parent class methods
named toString and calculateEarnings methods.
→Create a class HourlyEmployee which is a sub class of employee and has two private attributes of
double data type named wage and hours. The class shall also comprise public methods for initializing and
accessing its private fields. The class shall also comprise two methods that override the parent class methods
named toString and calculateEarnings methods.
→Create a class CommisionedEmployee which is a sub class of employee and has two private attributes
of double data type named grossSale and commissionRate. The class shall also comprise public methods for
initializing and accessing of its private fields. The class shall also comprise two methods that override the
parent class methods named toString and calculateEarnings methods.
→Create a class BaseSallariedCommisionedEmployee which is a sub class of CommissionedEmployee
and has one private attributes of double data type named baseSallary. The class shall also comprise public
methods for initializing and accessing of its private fields. The class shall also comprise two methods that
override the parent class methods named toString and calculateEarnings methods.
→Other implementation details:
For salaried employees, their income is fixed income which is paid in a weekly basis.
For hourly employees, their income is calculated just by multiplying the number of hours worked by
the hourly salary rate for the first 40 hours but the work which is done outside the 40 hour time frame will
be considered as overtime and calculated by multiplying the number of hours worked by the hourly salary
rate by 1.5.
For commissioned employees, their income is calculated by multiplying the gross salary by commission
rate. For base salaried commissioned employees their income is calculated by multiplying the gross sale by
commission rate and adding the base salary.
The method toString() is used to return a the employee information including first name, last name,
social security number and weekly earnings.
Finally create a class named EmployeeTest and implement following code and report what you under-
stand to your respective laboratory session instructor.
public class EmployeeTest
{
public static void empDescription(Employee e) {
System.out.println(e.toString());
}
public static void main(String args[ ])
{
SalariedEmployee se=new SalariedEmployee();
se.setWeeklySalary(9000);
HourlyEmployee he=new HourlyEmployee();
he.setHour(89);
he.setWage(1000);
CommisionedEmployee ce=new CommisionedEmployee();
ce.setComissionRate(0.19);
ce.setGrossSale(20000);
BaseSalariedCommisionedEmployee bsce=new BaseSalariedCommisionedEmployee();
bsce.setBaseSalary(9000);
bsce.setComissionRate(0.20);
bsce.setGrossSale(100000);
Employee e[]=new Employee[4];
e[0]=se;
e[1]=he;
e[2]=ce;
e[3]=bsce;
for(Employee myEmp:e)
{

May 13, 2017 Compiled by: Hailemelekot D. Page 15


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

if(myEmp instanceof BaseSalariedCommisionedEmployee)


{
BaseSalariedCommisionedEmployee
emp=(BaseSalariedCommisionedEmployee)myEmp;
emp.setBaseSalary(4000);
emp.setComissionRate(0.15);
emp.setGrossSale(10000); System.out.println(myEmp);
}
else if(myEmp instanceof CommisionedEmployee)
{
CommisionedEmployee
emp=(CommisionedEmployee)myEmp;
emp.setComissionRate(0.15);
emp.setGrossSale(10000);
System.out.println(myEmp);
}
else if(myEmp instanceof HourlyEmployee)
{
HourlyEmployee emp=(HourlyEmployee)myEmp;
emp.setWage(1000); emp.setHour(50);
System.out.println(myEmp);
}
else if(myEmp instanceof SalariedEmployee)
{
SalariedEmployee emp=(SalariedEmployee)myEmp;
emp.setWeeklySalary(5000);
System.out.println(myEmp);
}
}
/*
Calling the empDiscription method with instance of SalariedEmployee class
*/
System.out.println(“\n \n The result of polymorphic method call”);
System.out.println(“\n \nCalling the empDiscription method using instance of
SalariedEmployee class as an arguement”);
empDescription(se);
/*
Calling the empDiscription method with instance of HourlyEmployee class
*/
System.out.println(“\n Calling the empDiscription method using instance of
HourlyEmployee class as an arguement”);
empDescription(he);
/*
Calling the empDiscription method with instance of CommisionedEmployee class
*/
System.out.println(“\nCalling the empDiscription method using instance of
CommisionedEmployee class as an arguement”);
empDescription(ce);
/*
Calling the empDiscription method with instance of
BaseSalariedCommisionedEmployee class
*/
System.out.println(“\n Calling the empDiscription method using instance of
BaseSalariedCommisionedEmployee class as an arguement”);
empDescription(bsce);
}
}

May 13, 2017 Compiled by: Hailemelekot D. Page 16


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #8
(Exception Handling)

Objective
• Familiarizing about the concept of exception handling using Java programming language.

Preparation Tasks
• Understanding/Revising the concepts of exception handling which is dealt in the lecture class.

Activities
a. Create a Java program prints the contents of an initialized array to the console screen using for loop. The
program shall handle the exception if the iteration moves beyond the array size. The exception shall be
handled using try catch blocks.

b. Create a Java program that prints the contents of an initialized array to the console screen using for loop.
The program shall handle the exception if the iteration moves beyond the array size. The exception shall
be handled using throw statements.
c. Take array of string from the user and convert to the corresponding array of integers and calculates the
average. While implementing your code you are expected to catch related exceptions which include: Ar-
rayIndexOutOfBounds, IllegalArgumentException, ArithemeticException and finally include Exception block
to handle the general exception. In addition, at the end, try to include finally block and implement anything
you need with the program. 3
d. Create and test your own custom exception named InvalidAgeValueException and InvalidGenederValueEx-
ception based on the following rule. The first exception is thrown if the person inters the age of a person
which is either less than 0 or greater than 130 and the second exception is thrown if the person inters the
character value other than ’M’ or ’F’ for gender filed of your console program.

3 Note: For this question you are expected to build a complete try. . .catch. . .finally block.

May 13, 2017 Compiled by: Hailemelekot D. Page 17


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming(ECEG-3162)
Laboratory Exercises #9
(Introduction to Graphical User Interfaces(GUI))

Objective
• Introducing the basics of Graphical User Interface(GUI) programming using Java programming language.

Preparation Tasks
• Understanding the basic concepts of graphical user interfaces that is dealt at the lecture time.

Activities
a. Develop a Java GUI application that displays an empty window that has a size of 300 pixel by 300 pixel and
has a background color red.
→ Add a label to the previous window that you develop in step one to display the text “Hello Guys from
GUI App.!”
→ In Addition to the label, add a button control to your GUI application.
b. Develop a simple Java GUI application called click counter that displays how many times a button is clicked
to the console Screen. For instance, if the button is clicked once, the program shall “You clicked me 1
times!” and if the button is clicked two times, the program shall display “You clicked me 2 times!”. . .

c. Modify the above program to display the above button click message on a label rather than at the console
screen;
d. Develop a Java swing application that takes two numbers from the user using two text fields and displays
their sum, product, difference and division on a label. The user preference of the four options shall be taken
by two options: one by separate button for each operations and one by using combo box. Both options shall
be fully implemented and be fully functional.
e. Develop GUI based application for the fraction class that you implemented to demonstrate the abstract data
types in your previous laboratory exercise.
f. Develop a simple calculator using Java Swing GUI application. The functionality requirement of the applica-
tion shall be as your preference but it must have at least the basic functionality expected from common simple
calculators but you are free to use your own preference with regard to graphics and related implementations.

May 13, 2017 Compiled by: Hailemelekot D. Page 18


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

Addis Ababa University


Addis Ababa Institute of Technology
School of Electrical and Computer Engineering
Object Oriented Programming)
Optional Laboratory Exercises #10
(Introduction to Java Database Connectivity (JDBC))

Objective
• Introducing Java database programing using JDBC

Preparation Tasks
• In order to be successful in this lab session having a basic knowledge of database is a must. So, students are
required to read about the basics of database concepts before attending the laboratory classes.

Activities
a. JDBC overview The JDBC (Java Database Connectivity) API defines interfaces and classes for writing
database applications. Using JDBC any SQL, PL/SQL statements can be sent to almost any relational
database. JDBC is a Java API for executing SQL statements and supports basic structured query lan-
guage(SQL) functionality. It provides access to relational database management system by allowing the
feature to embed SQL inside Java code. By using JDBC API, it is possible to create a table, insert values
into a table, query the table, retrieve results, update the table and perform other related tasks with DBMS.
In order to process SQL using JDBC you shall use the following steps:
- Establishing a connection.
-Create a statement.
- Execute the query.
- Process the ResultSet object.
-Close the connection

b. Step by Step Example to Connect MySQL Database Using JDBC


(a) Load the JDBC driver {Class.forName(”com.mysql.jdbc.Driver”);}
(b) Specify the name and location of the database being used and connect to the database { Connection
connection = DriverManager.getConnection(
”jdbc:mysql://127.0.0.1:3306/databaseName”, ”MySQLServerUserName”,
”MySQLServerPassword ”);}
(c) Create a statement which is used to submit your query { Statement statement = connection.createStatement();}
(d) Execute a SQL query using a Statement object {
String sql=“SELECT * FROM department;”4
ResultSet resultset = statement.executeQuery(sql);}
(e) Get the results in a ResultSet object {
while(resultset.next())
{
String departmentName = resultset.getString(“departmentName”);
5
double budget = resultset.getDouble(“budget”);
String building = resultset.getString(“building”);

/* do the processing staff here :) */


}
}
4 Note:For inserting, updating, and deleting data from a table, just create sql string, let’s say it is named as sql’ and just execute

this: statement.executeUpdate(sql);
5 The School System database will is a sample database which is created for this lab and it be provided while conducting the lab.

The department table is found in that sample database.

May 13, 2017 Compiled by: Hailemelekot D. Page 19


Object Oriented Programming (ECEG-3162) Laboratory Exercises Version: 2.0

(f) Finish by closing the ResultSet , Statement and Connection objects { resultset.close(); , statement.close();
, connection.close(); }6

c. Practical Exercises
-Using the school system database and the data in the school system database do the following exercises
using Java programming language and JDBC API:
Select all the data in the department table and display them to the console screen.
Insert the following data into the department table. department name = CSE, build- ing=Amist
Killo, budget=50,000,000, country=Ethiopia
Update the budget of CSE department to be 60,000,000 and building to be SAMSUNG.
delete all the record from the department table where department name is CSE.

6 Note that: Don’t forget to catch the appropriate exceptions as SQL related exceptions are checked exceptions.

May 13, 2017 Compiled by: Hailemelekot D. Page 20

You might also like