Object Oriented Programming - Mid - Solution-2
Object Oriented Programming - Mid - Solution-2
OBJECT ORIENTED
PROGRAMMING
CSE 1115
SOLUTION BY
NURUL ALAM ADOR
nurulalamador.github.io/UIUQuestionBank
Index
Trimester Page
Spring 2024 3
Fall 2023 8
Summer 2023 18
Spring 2023 26
Fall 2022 35
nurulalamador.github.io/UIUQuestionBank 2
Spring 2024
class Point2D
{
int x, y;
public Point2D(int x, int y){
this.x = x;
this.y = y;
System.out.println("Point2D constructor");
}
public String Display(){
//write codes here
}
}
class Point3D extends Point2D{
int z;
//write codes here
}
Now:
I. Complete the “Display” method of the Point2D class that prints all the instance
variables,
II. Add a constructor in the Point3D class that uses the base class constructor,
III. Add another method “Display” in the Point3D class. You have to use the parent’s
“Display” method here, so that the output looks like this:
Point2D constructor
x = 1, y = 2
Point2D constructor
Point3D constructor
x = 5, y = 4, z = 3
Solution:
The code has been rewritten below with the necessary changes:
class Point2D {
int x, y;
public Point2D(int x, int y) {
this.x = x;
this.y = y;
nurulalamador.github.io/UIUQuestionBank 3
System.out.println("Point2D constructor");
}
public String Display() {
return ("x = "+x+", y = "+y);
}
}
Solution:
nurulalamador.github.io/UIUQuestionBank 4
The code has been rewritten below with the necessary modification:
class Myparent {
private int p;
public final int myfunction() {
return p*p;
}
public void set_p(int Q) { p = Q; }
public Myparent(int p) {
this.p = p;
}
public int get_p() { return p; }
}
class Mychild extends Myparent{
public Mychild(int K){ super(K); }
public Mychild(){
super(0);
}
double myroot() {
return Math.sqrt(get_p());
}
}
nurulalamador.github.io/UIUQuestionBank 5
System.out.println(Person.s);
}
}
Solution:
Output:
3
1
2
3
1
13
11
4. Suppose that you visit a village market where fresh vegetables and fishes are sold. The
sellers sell their items with a profit of 𝑧% of their production cost 𝑐 . Typical items are
given by the following Table:
The class FoodItem that includes type 𝑡, production cost 𝑐 and profit 𝑧 as public
variables and a method findprice() is given as follows:
Next, two derived classes Vegetable and Fish are given as follows.
nurulalamador.github.io/UIUQuestionBank 6
public class Fish extends FoodItem{
public void setparameter(){
if(t == "Carp"){ c = 20; z = 15; }
else if(t == "medium"){c = 25; z = 20;}
else if(t == "small"){c = 200; z = 25;}
}
public Fish(String t){
this.t = t;
}
}
Now as a programmer, test the above classes in the main method in a new class
MyTest by finding your total purchase price if you buy 3Kg fish of type small and 2 Kg
vegetable of type Cauliflower. [Make 2 objects of FoodItems and use the child class
references to a FoodItems class object. Then call appropriate methods e.g.,
setparameter, getprice.]
Solution:
MyTest class has been written below with the necessary code:
((Fish)fish).setparameter();
((Vegetable)vegetable).setparameter();
System.out.println(totalPrice);
}
}
nurulalamador.github.io/UIUQuestionBank 7
Fall 2023
1. a) Logarithms are mathematical functions of the form log 𝑏 𝑥 which consists of two
parts: base (int b) and argument (double x). The logarithmic value is calculated
using the formula:
log 𝑒 𝑥
log 𝑏 𝑥 =
log 𝑒 𝑏
Where log 𝑏 𝑥 can be evaluated by Java code as Math.log(x).
You have to write a class Logarithm and include the member variables b and x,
different types of constructors and a function myfunc() to evaluate log 𝑏 𝑥 such
that the Main generates the output provided in the following table:
Output
2 9.0 3.0
2 9.0 3.0
0 0.0 0.0
Solution:
Logarithm class has been written below:
class Logarithm {
int b;
double x;
nurulalamador.github.io/UIUQuestionBank 8
return 0.0;
} else {
double result = Math.log(x)/Math.log(b);
return Math.floor(result);
}
}
}
Solution:
Output:
nurulalamador.github.io/UIUQuestionBank 9
public String name;
private String account_id;
private double balance;
BankAccount(String name, double balance, String gender){
this.name=name;
this.balance=balance;
this.account_id=gender+"-"+name;
}
//Add necessary codes here
}
class Test{
public static void main(String[] args) {
BankAccount b=new BankAccount("Mr.Rahman",1000, "M");
System.out.println("Account id:"+b.account_id);
System.out.println("balance before:"+b.balance);
b.balance = b.balance - 2000;
}
}
Rewrite the codes after correcting the errors by adding necessary getter/setter
methods to access private variables. Do not change access modifiers of member
variables. While updating the balance, a condition that balance cannot be less
than 0 should be considered.
Solution:
The codes has been written below with necessary changes:
nurulalamador.github.io/UIUQuestionBank 10
class Test{
public static void main(String[] args) {
BankAccount b=new BankAccount("Mr.Rahman",1000, "M");
System.out.println("Account id:"+b.getAccount_id());
System.out.println("balance before:"+b.getBalance());
b.setBalance(b.getBalance() - 2000);
}
}
class Order{
public static void main(String[] args) {
PizzaShop p=new PizzaShop();
p.order(2,4);
p.order(1,2,1);
p.order(3);
}
}
Write the necessary missing codes so that the following output is produced when
the program runs:
Solution:
The codes has been written below with necessary changes:
PizzaShop(){
System.out.println("Welcome to pizza shop");
}
nurulalamador.github.io/UIUQuestionBank 11
public void order(int noOfPizza) {
int totalBill = noOfPizza*pizza_price;
System.out.println("You ordered "+noOfPizza+" pizzas");
System.out.println("Total bill: " + totalBill + " taka");
}
public void order(int noOfPizza, int noOfDrink) {
int totalBill = noOfPizza*pizza_price
+ noOfDrink*drink_price;
System.out.println("You ordered " + noOfPizza + " pizzas, "
+ noOfDrink + " drinks");
System.out.println("Total bill: "+totalBill+" taka");
}
public void order(int noOfPizza, int noOfDrink, int noOfFries) {
int totalBill = noOfPizza*pizza_price
+ noOfDrink*drink_price + noOfFries*fries_pri]ce;
System.out.println("You ordered " + noOfPizza +" pizzas,"
+ noOfDrink + " drinks," + noOfFries + " drinks");
System.out.println("Total bill: "+totalBill+" taka");
}
}
class Vehicle {
private String make;
private String model;
public Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public void start() {
System.out.println("[Vehicle] The vehicle is starting.");
}
public void stop() {
System.out.println("[Vehicle] The vehicle is stopping.");
}
public void drive() {
System.out.println("[Vehicle] The vehicle is moving.");
}
}
nurulalamador.github.io/UIUQuestionBank 12
public class Main {
public static void main(String[] args) {
Vehicle car1 = new Car("make001", "model001", 4);
car1.drive();
car1.honk();
}
}
Solution:
The Car class has been created below:
There will be an error if we execute the code in the given Main class. Here, the variable
type of car1 is a Vehicle, and the instance type is Car, which is known as Polymorphism.
For this reason, the car1 variable will be able to access only these methods, which are
overriding in child class Car from parent class Vehicle. Since the honk() function does
not exist in the parent class Vehicle, it will throw an error.
4. Think about your own startup Uthao which is a ride sharing program using Java. Now
due to our country’s rules and regulations, vehicles on your platform must abide by the
speedLimit at 80 km/h.
(a) Create a class name Ride that contains an attribute speedLimit which
Cannot get changed by its child classes
Cannot get changed once assigned
Will contain an Integer value
Must be static
Now create the following child classes of Ride:
Bike
Car
Microbus
Each child of Ride (that is, Bike, Car and Microbus) will receive a penalty for
exceeding the speedLimit.
All the child classes have the following initial_speed and acceleration:
Bike: initial_speed 20 km/h , acceleration 2 km/h
Car: initial_speed 40 km/h, acceleration 10 km/h
Microbus: initial_speed 15 km/h, acceleration 5 km/h
nurulalamador.github.io/UIUQuestionBank 13
Now do the following tasks:
(b) Create a method named getHighestAccelerationTime() ( return type: double )
which will find out the time needed for a ride to reach the speedLimit by using
the formula : 𝑣 = 𝑢 + 𝑎𝑡
(c) Create a method named calculateFine( int hour ) (return type: double ) which
will calculate the fine for each vehicle by following the implementation below:
Bike: Base fine will be 50 TK and for each hour exceeding speedLimit, it will
add an extra 100 TK
Car: Base fine will be 100 TK and for each hour exceeding speedLimit, it will
add an extra 150 TK
Microbus: Total fine will be 3000 TK for just exceeding speedLimit.
(d) Find out the output of the following Code:
Solution:
The necessary codes for (a), (b) and (c) have been written below:
class Ride {
static final int speedLimit = 80;
double initial_speed;
double acceleration;
double baseFine;
double extraFine;
double getHighestAccelerationTime() {
/* From v = u + at,
t = (v - u)/a
Here, u = initial-speed
v = speedLimit
a = acceleration
*/
return (speedLimit - initial_speed)/acceleration;
}
nurulalamador.github.io/UIUQuestionBank 14
} else {
return 0;
}
}
}
5. a) Can you define an abstract method in a non-abstract class? Provide a reason for
your answer.
Solution:
No, we cannot define an abstract method in a non-abstract class in Java. This is
because an abstract method is inherently a method that lacks an implementation
and is meant to be implemented by subclasses. By definition, if a class contains at
least one abstract method, the class must be declared as abstract.
5. b) An abstract class cannot contain variables. Do you agree with the statement?
Provide a reason for your answer.
nurulalamador.github.io/UIUQuestionBank 15
Solution:
No, I do not agree with the statement. An abstract class can contain variables. In
Java, an abstract class can have variables, and these can be of any type (instance
variables, static variables, final variables, etc.). Not only variables, but abstract classes
can also contain complete methods. But interfaces cannot contain variables or
complete methods in Java. The primary restriction on abstract classes is that they
cannot be instantiated directly, without creating any child class.
5. Suppose that you are tasked with modeling a library system for various types of
reading materials. You will be working with books, magazines. Each type of reading
material has different properties.
Thus, you are required to accomplish the following tasks:
nurulalamador.github.io/UIUQuestionBank 16
iii. Now override the “displayDetails()” method to display the details of the book,
including its title, author, year, and genre.
Solution:
Subclass Book has been written below:
void displayDetails() {
System.out.println("Title: " + getTitle());
System.out.println("Author: " + getAuthor());
System.out.println("Year: " + getYear());
System.out.println("Genre: " + genre);
}
}
void displayDetails() {
System.out.println("Title: " + getTitle());
System.out.println("Author: " + getAuthor());
System.out.println("Year: " + getYear());
System.out.println("Issue Number: " + issueNumber);
}
}
nurulalamador.github.io/UIUQuestionBank 17
Summer 2023
static {
System.out.println("Initializing Vehicle class...");
}
{
System.out.println("Initializing an instance of the Vehicle
class...");
}
public Vehicle() {
System.out.println("Creating a default vehicle.");
brand = "Unknown";
}
Solution:
nurulalamador.github.io/UIUQuestionBank 18
Output:
nurulalamador.github.io/UIUQuestionBank 19
operatingSystem, String IMEI) {
super(brand, price);
this.model = model;
this.operatingSystem = operatingSystem;
this.IMEI = IMEI;
}
3. Suppose that you are assigned to compute the volumes of different geometrical
objects, i.e., cylinder, sphere and cone. Thus, you are required to do the tasks
systemically as follows:
Write a Java Class called Myobject that has a private member variable: 𝑟 which
represents radius of the shape. Add the following function: findVolume() that
returns -1.0 (since no geometrical object is given).
Write a child class Sphere from Myobject. Include the function findVolume()
that computes the volume 𝑣 of a sphere as follows:
4 3
𝑣= 𝜋𝑟
3
Write another child class Cylinder from Myobject. Include a private variable ℎ
and the function findVolume() that computes the volume 𝑣 of a cylinder as
follows:
𝑣 = 𝜋𝑟 2 ℎ
Write a child class Cone from Cylinder. Include the function findVolume() that
computes the volume 𝑣 of a cone as follows:
1 2
𝑣= 𝜋𝑟 ℎ
3
Add only the necessary Getter methods for each variable in the above classes.
Make the necessary parameterized constructors to set the values of the
variables.
Now test your program from main by computing the volumes of different
geometrical objects provided in Table 1.
Table 1: List of different geometrical objects and their radius and heights (if applicable)
Myobject r h
Sphere1 2.5
Cone1 1.9 8.9
Cylinder1 1.5 6.5
Cone1 2.7 5.7
Sphere1 3.5
nurulalamador.github.io/UIUQuestionBank 20
Hint: Make 5 objects of Myobjects and use each child class reference to each of these
objects according to Table 1 using the concept of heterogeneous collection. Next, sum
up the volumes which can be obtained by calling the function findVolume() through
each object.
Solution:
The program has been completed below:
nurulalamador.github.io/UIUQuestionBank 21
double r1 = getr();
double h1 = geth();
double x = Math.PI * r1*r1*h1/3.0;
return x;
}
double v = 0.0;
double t;
4. Consider the following two classes and the output of the program. Read the
comments carefully, correct errors in the code of the following StaticContext class,
and rewrite the code for the StaticContext class. You can edit, add, or remove any
lines excluding the commented ones. You can also write necessary constructors and
blocks in the StaticContext class if required.
package rollbar;
package rollbar;
public class StaticContext {
final static int value; //You can't modify or remove this line
of code
private double mark;
nurulalamador.github.io/UIUQuestionBank 22
private int count;
public void calculate(){
System.out.println("calculate method is called");
}
Expected Outcome:
count= 2
value = 8
mark= 90.0
calculate method is called
Solution:
The program has been written below with the necessary modifications:
package rollbar;
public class FinalContext {
public final void calculate(){
System.out.println("calculate method is called");
}
}
package rollbar;
public class StaticContext extends FinalContext {
private final static int value;
private double mark;
private static int count;
static {
value = 8;
count = 0;
}
StaticContext(){
mark = 90;
}
nurulalamador.github.io/UIUQuestionBank 23
return ++count;
}
private double getMark() {
return mark;
}
5.1 a) Can a class be abstract and final simultaneously? Why or why not?
Solution:
No, because by making an abstract class final, you are also restricting it from being
inherited by other classes. So, there is no way to be able to even create a subclass
object which may be assigned to a variable of that abstract class.
5.1 b) Abstract classes can be created without a single instance variable of method
declared inside it. Can you think of any reason why you may want to create such
an abstract class?
Solution:
We may create an abstract class without any instance variables or methods to
create a class hierarchy, where we do not want to add any features to the top
superclass.
5.1 c) Why does a class with an abstract method need to be declared abstract? (Just
answering “Compiler will give error” will not get you any marks)
Solution:
Since a method declared as abstract does not have any body, if an object of the
class with an abstract method is created, it won’t be able to execute that abstract
method and would give error. To prevent making the abstract method get called,
we declare the entire class as abstract so that an object of that class cannot be
initialized
[ P.T.O ]
nurulalamador.github.io/UIUQuestionBank 24
abstract class Animal {}
Now, complete the speak method such that it prints (You cannot change any other
part of the program other the speak method)
i. “WAAHHH” if the variable target is instance of the class Baby,
ii. “Meow” if the variable target is instance of the class Cat,
iii. “Grrrrr” if the variable target is instance of any other subclass of Animal
Solution:
The speak method has been completed below:
nurulalamador.github.io/UIUQuestionBank 25
Spring 2023
Solution:
Output:
2. Consider the following three classes and the output of the program. Then answer
(a),(b) and (c).
package M1;
nurulalamador.github.io/UIUQuestionBank 26
}
package M1.M2;
if (m1.eat(h1)==true) {
System.out.println("Monster has eaten human "+h1.id);
}else{
System.out.println("Human escaped");
}
System.out.println(m1.scare(h2.bravery));
}
}
Expected Outcome:
To avoid getting scared or eaten be brave or intelligent.
To avoid getting scared or eaten be brave or intelligent.
New weight of monster=110.0
Monster has eaten human 1
Human is too brave to scare
a) Correct the given code (don’t modify the methods yet) by editing or adding any
lines. You cannot remove any line from the code. Also write necessary getter
methods (Assume the variables are readonly).
b) Observe the output given and write necessary constructors and blocks accordingly.
c) Implement the eat() and scare() methods. The eat() method checks the intelligence
of a human- if it’s “high”, returns true, otherwise it calls the increaseWeight()
method and then returns false. The scare() method checks a human’s bravery- if
it's false, it prints a line: “Human scared." otherwise it will print:
"Human is too brave to scare."
nurulalamador.github.io/UIUQuestionBank 27
Solution:
a) The program has been written below with correction:
package M1;
public class Human {
private int id;
private String intelligence; // Make intelligence private
protected boolean bravery;
package M1;
nurulalamador.github.io/UIUQuestionBank 28
c) The eat() and scare() method have been implemented below:
nurulalamador.github.io/UIUQuestionBank 29
Expected output
Subtraction result: -1
Summation result: 15
nurulalamador.github.io/UIUQuestionBank 30
count++;
System.out.println("I am in a Child Class: " + count);
}
}
public class Main {
public static void main(String[] args) {
Child x = new Child();
x.printDetails();
x.printDetails();
Parent y = new Parent();
y.printDetails();
Child.printDetails();
Parent.printDetails();
x.printDetails();
}
}
Solution:
Output:
I am in a Child Class: 1
I am in a Child Class: 2
I am in Parent Class: 3
I am in a Child Class: 4
I am in Parent Class: 5
I am in a Child Class: 6
5. Find out the errors in the following code and explain the reasons of Errors in those
particular lines.
class Point{
int x, y;
final int f = 10;
final Point p = new Point(1, 2);
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
class Check{
public static void main(String args[]){
Point point = new Point(5, 5);
point.f = 5;
point.p.x = 10;
point.p = new Point(1, 5);
}
}
Solution:
The program has been written below with correction:
class Point {
int x, y;
nurulalamador.github.io/UIUQuestionBank 31
int f = 10;
// Removing final keyword to prevent error while changing it
Point p = null;
/* Declaring p as null to initialize it later, otherwise
reinitializing this object will throw error */
nurulalamador.github.io/UIUQuestionBank 32
super(n, r);
quantity = q;
}
//override calcPrice & printDetails
}
class Main{
public static void main(String[] args) {
Cake cake[];
a) calcPrice() method in the Cake class is used to calculate the total price of a cake.
You need to override this method in each of the derived classes: OrderCake and
ReadymadeCake. Price is calculated as per the following rules:
OrderCake: rate * weight
ReadymadeCake: rate * quantity
Also, override another method printDetails() in each class. This method will print
the information about a particular cake according to the following format:
Name: <name>
Rate: <rate>
Weight/Quantity: <value>
Total Price: <price>
Now, complete the OrderCake and ReadymadeCake class by overriding calcPrice()
and printDetails() methods.
b) Create an array of three cake objects. First two objects are of OrderCake type and
later one object is of ReadymadeCake type in the main() method. Assign some
values to the class attributes while creating those objects. If you successfully
create the array, your output will look like as follows:
Name: OrderCake
Rate: 150
Weight: 3
Total Price: 450
… …. … …. ….. …
Name: ReadymadeCake
Rate: 200
Quantity: 2
Total Price: 400
…. …… …… …… …… ..
Solution:
a) The program has been completed below:
nurulalamador.github.io/UIUQuestionBank 33
public OrderCake(String n, double r, double w) {
super(n, r);
weight = w;
}
class Main {
public static void main(String[] args) {
Cake cake[] = new Cake[3];
nurulalamador.github.io/UIUQuestionBank 34
Fall 2022
nurulalamador.github.io/UIUQuestionBank 35
Solution:
Output:
Valar dohaeris
Valar morghulis
Best TV series after Breaking Bad
Valar dohaeris
Valar morghulis
John Snow 404
Impact: 0.0
Intent: 0.0
Daenerys Targaryen
Impact: 4.8
Intent: 0.0
2. A Class named Movie containing following elements: name (String), origin (String),
genre (String) and rating (Float). Among them, name cannot be accessed outside the
class and origin can only be accessed in inherited class. Other two elements can be
accessed from anywhere.
Write down the Movie Class which will contain following members:
a. Provide appropriate Access Modifier to the elements.
b. Create Necessary Methods to access name and origin from outside the class.
c. Two Parameterized Constructors where First Constructor will take all four
elements and Second Constructor will take only name and genre.
d. A method named void Details() that will print the details of the Movie in
following format:
Solution:
The Movie class has been written below:
nurulalamador.github.io/UIUQuestionBank 36
public String getName() {
return name;
}
public String getOrigin(){
return origin;
}
3. package transport;
package publicTransport;
Bus(int licenseNo){
super.noOfWheels = 4;
this.licenseNo = licenseNo;
}
}
Rewrite the above blocks of code with the following changes.
Make sure no other classes have direct access to ‘noOfWheels’ in ‘Vehicle’.
Make Sure ‘noOfWheels’ in ‘Vehicle’ is read-only both from inside and outside of
the ‘transport’ package. (the value can be set only within the constructor)
Make sure the ‘Bus extends Vehicle’ line does not throw any error.
Resolve any error that might be thrown by the constructor of class ‘Bus’.
Enable read and write access to ‘licenseNo’ of the class ‘Bus’ without changing
the given access modifier.
Solution:
The program has been rewritten below with necessary changes:
nurulalamador.github.io/UIUQuestionBank 37
package transport;
package publicTransport;
4. All of you know that FIFA 2022 with Brazil, Argentina controversy is a trendy topic.
Given the following UML diagram, which has three classes: Fifa, BrazilFans, and
ArgentinaFans. Although each detail is depicted in the UML diagram, some of the
more complex parts are written here for convenience.
nurulalamador.github.io/UIUQuestionBank 38
There are 3 Classes. Fifa, BrazilFans and ArgentinaFans.
Fifa() constructor prints "Who will be winner?" message. The first line of the
Fifa(int,String) constructor body is called Fifa() constructor with the help of this
keyword, and the remaining two lines instantiate variables using this keyword.
toString() methods return a string with the given format.
BrazilFans is a derived class of Fifa, which has a constructor with three parameters, the
first two of which are passed to the base class, and the last one is used to instantiate
variables using this keyword. toString() methods return a string with the given format.
The incrementWorldCups() methods increase the value of havingWorldCups by 1
when it is invoked.
Mid is another class that contains main() methods. In the main() method, after creating
objects of ArgentinaFans and BrazilFans, if the noOfGoals of Argentina is greater than
Brazil, then the incrementWorldCups() method of ArgentinaFans is called; otherwise,
the incrementWorldCups() method of BrazilFans is called. Write the whole program
appropriately so that when it executes, you get the following output:
Solution:
The program has been written below:
class Fifa {
private int noOfGoals;
String venue;
{
System.out.println("Who will be winner?");
}
nurulalamador.github.io/UIUQuestionBank 39
return noOfGoals;
}
}
{
System.out.println("Brazil will win");
}
void incrementWordCups(){
havingWorldCups++;
}
}
{
System.out.println("Argentina will win");
}
void incrementWordCups(){
havingWorldCups++;
}
}
System.out.println(argentinaFans);
System.out.println(brazilFans);
nurulalamador.github.io/UIUQuestionBank 40
if(argentinaFans.getNoOfGoals() > brazilFans.getNoOfGoals()){
argentinaFans.incrementWordCups();
} else{
brazilFans.incrementWordCups();
}
System.out.println(argentinaFans);
System.out.println(brazilFans);
}
}
5. class PClass {
void mFnc(){
System.out.println("Hello from P Class!");
}
class Main{
public static void main(String[] args) {
PClass pObj = new PClass();
CClass cObj = new CClass();
pObj.mFnc();
cObj.mFnc();
cObj.mFnc(10, 2.99);
cObj.mFnc(3.145);
}
}
b) “In the “CClass” which is a subclass of “PClass”, both Method Overriding and
Method Overloading has been demonstrated”- Explain the statement using the
examples from the code snippet.
nurulalamador.github.io/UIUQuestionBank 41
Solution:
a) Output:
b) In the “CClass” which is a subclass of “PClass”, both Method Overriding and Method
Overloading has been demonstrated.
Method Overloading occurs when multiple methods have the same name but
different parameter lists within the same class. Here, in both “CClass” and “PClass”,
the mFnc method is overloaded to accept different parameters such as (void),
(double), (int and double), allowing different behaviors based on the arguments
passed.
nurulalamador.github.io/UIUQuestionBank 42