Object Oriented Programming Lab
Object Oriented Programming Lab
LABORATORY MANUAL
Create an employee class (id, name, deptname, salary). Define a default and parameterized
constructor and create two objects of that class.
int id;
String name;
String deptname;
double salary;
// Default Constructor
public Employee() {
this.id = 0;
this.name = "";
this.deptname = "";
this.salary = 0.0;
// Parameterized Constructor
this.id = id;
this.name = name;
this.deptname = deptname;
this.salary = salary;
1-Activity Create a class, Heater that contains a single integer field, temperature. Define a
constructor that takes no parameters. The temperature field should be set to the value 15 in the
constructor. Define the mutators warmer and cooler, whose effect is to increase or decrease the
value of the temperature by 5 respectively. Define an accessor method to return the value of
temperature.
2-Modify your Heater class to define three new integer fields: min, max, and increment. The values
of min and max should be set by parameters passed to the constructor. The value of increment
should be set to 5 in the constructor. Modify the definitions of warmer and cooler so that they use
the value of increment rather than an explicit value of 5. Before proceeding further, check that
everything works as before. Now modify the warmer method so that it will not allow the
temperature to be set to a value larger than max. Similarly modify cooler so that it will not allow
temperature to be set to a value less than min. Check that the class works properly. Now add a
method, setIncrement that takes a single integer parameter and uses it to set the value of increment.
Once again, test that the class works as you would expect it to, by creating some Heater objects.
Do things still work as expected if a negative value is passed to the setIncrement method? Add a
check to this method to prevent a negative value from being assigned to increment.
package heater;
public Heater() {
this.temperature = 15;
this.temperature += 5;
this.temperature -= 5;
return this.temperature;
heater.warmer();
heater.cooler();
this.temperature = 15;
this.min = min;
this.max = max;
this.increment = 5; }
this.temperature += this.increment;
} else {
this.temperature = this.max; } }
this.temperature -= this.increment;
} else {
this.temperature = this.min; } }
return this.temperature; }
if (increment >= 0) {
this.increment = increment;
} }
heater1.warmer();
heater2.cooler();
heater1.setIncrement(-5);
heater1.warmer();
System.out.println("Temperature of heater1 after setting negative increment and calling warmer(): " + heater1.getTemperature());
}
Dr. Salah Alghyaline
}
Week-3
1. Create a new project according to the following:
import java.util.Scanner;
public static int addNumbers(int num1, int num2, int num3, int num4)
{
return num1 + num2 + num3 + num4;
}
public static void main(String[] args) {
int sum1 = SecondClass.addNumbers(5, 10);
int sum2 = SecondClass.addNumbers(5, 10, 15);
int sum3 = SecondClass.addNumbers(5, 10, 15, 20);
System.out.println("Sum1: " + sum1);
System.out.println("Sum2: " + sum2);
System.out.println("Sum3: " + sum3);
Create a class called Time that has separate int member data for hours, minutes, and seconds.
Provide
// no-argument constructor
public Time() {
hours = 0;
minutes = 0;
seconds = 0; }
// 3-argument constructor
result.seconds -= 60;
result.minutes++; }
result.minutes -= 60;
result.hours++; }
return result; }}
Create a class Employee that has a field for storing the complete name of employee (first and last
name), a field for storing the Identification number of employee, and another field for storing his
salary.
Provide
b) a 3-argument constructor for initializing the fields to values sent from outside.
c) a setter function (mutator) that sets the values of these fields by getting input from user.
e) Derive three classes from this employee class: Manager, Scientist, and Laborer. The manager
class has an additional data member of # of subordinates. Scientist class contains additional
information about # of publications. Laborer class is just similar to the employee class. It has no
additional capabilities. Derive a class foreman from the Laborer class that has an additional data
member for storing the percentage of quotas met by a foreman. Provide appropriate no-argument
and n-argument constructors for all the classes.
class Employee {
// No-argument constructor
public Employee() {
this.fullName = "";
this.idNumber = 0;
this.salary = 0.0;
// 3-argument constructor
this.fullName = fullName;
this.idNumber = idNumber;
this.salary = salary;
this.fullName = sc.nextLine();
this.idNumber = sc.nextInt();
this.salary = sc.nextDouble();
// No-argument constructor
public Manager() {
super();
this.numSubordinates = 0;
}
// 4-argument constructor
public Manager(String fullName, int idNumber, double
salary, int numSubordinates) {
super(fullName, idNumber, salary);
this.numSubordinates = numSubordinates;
}
// No-argument constructor
public Scientist() {
super();
this.numPublications = 0;
}
// 4-argument constructor
public Scientist(String fullName, int idNumber,
double salary, int numPublications) {
super(fullName, idNumber, salary);
this.numPublications = numPublications;
}
// 3-argument constructor
public Laborer(String fullName, int idNumber, double
salary) {
super(fullName, idNumber, salary);
}
}
// No-argument constructor
public Foreman() {
super();
this.percentQuotasMet = 0.0;
}
// 4-argument constructor
public Foreman(String fullName, int idNumber, double
salary, double percentQuotasMet) {
super(fullName, idNumber, salary);
this. percentQuotasMet;
}
• Two private instance variables: radius (of the type of double) and color (of the type String),
with default value of 1.0 and "red", respectively.
• Two overloaded constructors - a default constructor with no argument, and a constructor
which takes a double argument for radius.
• Two public methods: getRadius() and getArea(), which return the radius and area of this
instance, respectively. A public method called setRadius() to set he radius value.
// Default constructor
public Circle() {
this.radius = 1.0;
this.color = "red";
this.radius = radius;
this.color = "red";
return radius;
this.radius = radius;
}}
super(radius);
this.height = height; }
return height; }
}}
Dr. Salah Alghyaline
Week-7
Create a class called Point that has two data members: x- and y-coordinates of the point. Provide
a no-argument and a 2-argument constructor. Provide separate get and set functions for the each
of the data members i.e. getX, getY, setX, setY. The getter functions should return the
corresponding values to the calling function. Provide a display method to display the point in (x,
y) format. Make appropriate functions const.
Derive a class Circle from this Point class that has an additional data member: radius of the circle.
The point from which this circle is derived represents the center of circle. Provide a no-argument
constructor to initialize the radius and center coordinates to 0. Provide a 2-argument constructor:
one argument to initialize the radius of circle and the other argument to initialize the center of
circle (provide an object of point class in the second argument). Provide a 3-argument constructor
that takes three floats to initialize the radius, x-, and y-coordinates of the circle. Provide setter and
getter functions for radius of the circle. Provide two functions to determine the radius and
circumference of the circle.Write a main function to test this class.
package point;
private float x;
private float y;
public Point() {
x = 0; y = 0; }
this.x = x;
this.y = y; }
return x; }
return y;
this.x = x; }
this.y = y; }
p1.display();
p2.display();
p1.setX(1.0f);
p1.setY(1.5f);
p1.display();
c1.display();
c2.display();
c3.display();
c1.setRadius(3.0f);
c1.setX(1.0f);
c1.setY(1.5f);
c1.display();
public Circle() {
super();
radius = 0;
super(center.getX(), center.getY());
this.radius = radius;
super(x, y);
this.radius = radius;
return radius;
this.radius = radius;
}
Week-8
Imagine a publishing company that markets both book and audiocassette versions of its works.
Create a class publication that stores the title (type string) and price (type float) of a publication.
From this class derive two classes: book, which adds a page count (type int); and tape, which adds
a playing time in minutes (type float). Each of these three classes should have a getdata() function
to get its data from the user at the keyboard, and a putdata() function to display its data. Determine
whether public, private, or protected inheritance should be used. Justify your answer.
Write a main() program to test the book and tape classes by creating instances of them, asking
the user to fill in data with getdata() and then displaying the data with putdata().
import java.util.Scanner;
class Publication {
private String title;
private float price;
book.getData();
tape.getData();
System.out.println("Book details:");
book.putData();
System.out.println("Tape details:");
tape.putData();
}
}
Write a constructor which initializes the base and the height of a Triangle instance.
Write a method getArea() that returns the area of the Triangle as a double.
Write a method show(), to print the dimensions and area of the Triangle instance.
Write a method compare(Triangle t1, Triangle t2), which compares the area of two given
Triangle objects .
Write a method in circle class called calcarea to find the area of the circle.
import shapes2.circle;
this.radius = radius; }
this.base = base;
this.height = height;
return t1;
return t2;
} else {
return null; } }
if (largerTriangle != null) {
} else {
public TollBooth() {
totalCars = 0;
totalCash = 0.0;
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Q1 {
// File paths
// Initialize counters
int wordCount = 0;
int questionCount = 0;
int lineCount = 0;
String line;
wordCount += words.length;
// Count lines
lineCount++; }
} catch (IOException e) {
}
public Staff(String name, double salary) {
this.name = name;
this.salary = salary;
}
return salary+allowance;
}
return "Name= " + name + ", Salary = " + salary + ", Allowance = " + allowance + ", Paid = " + getPaid();
}
return salary+overtimPay;
}
// Define toString in Technician class
@Override
public String toString() {
Dr. Salah Alghyaline
return "Name= " + name + ", Salary = " + salary + ", Allowance = " + overtimPay + ", Paid = " + getPaid();
}
}
Week-13
Write a java code that:
A. Reads a text from data file D:\del\source.txt
B. Counts the words in the text and print the result or display it on the screen.
C. Finds out how many lines in the file and prints the result to another file
named D:\del\Backup.
D. Catches the exception if needed in you program.
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Q1 {
try {
String line;
int wordCount = 0;
int lineCount = 0;
int questionCount = 0;
wordCount += words.length;
// Count lines
lineCount++;
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace(); } }}
Dr. Salah Alghyaline
Week-14
import java.io.*;
} catch (IOException e) {
System.out.println("An error occurred: " +
e.getMessage());
}
}
}
100
9
-89
76
999999
0
-0.1
56
(a) Create a class MyFileManager having the main() loop. Using the BufferedReader class and
the try-catch-finally block, read the contents of numbers.txt.
(b) Inject an exception by giving the name of a non-existent file e.g. foo.txt. Remember to
release resources in the finally block.
(d) We have discussed in class that exception handling should not be used for input validation.
Modify the validateNumbers(...) method from part (c) to use input validation for handling
negative numbers gracefully.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
super(message); }}
class MyValidator {
if (Double.parseDouble(num) < 0) {
} } }}
BufferedReader br = null;
try {
String line;
try {
MyValidator.validateNumbers(line);
System.out.println(line);
} catch (NegativeNumberException e) {
} catch (IOException e) {
} finally {
try {
if (br != null) {
br.close(); }
} catch (IOException e) {