0% found this document useful (0 votes)
38 views109 pages

Inheritance in Java: Access Modifiers

Here are the answers to the questions: Part 1: MCQ 1. d 2. e 3. a 4. d 5. c Part 2: Question 2 A. The code in line 1 is valid. It creates a Mobile object without passing any parameter to the constructor, so the default value of 0 will be assigned to price. B. The code in line 2 will cause a compilation error, because the Mobile object m1 does not have its price variable initialized. We need to either pass a parameter to the constructor or set the price explicitly before printing. C. Mobile[] mobiles = new Mobile[2]; mobiles[0] = new

Uploaded by

malik8sabah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views109 pages

Inheritance in Java: Access Modifiers

Here are the answers to the questions: Part 1: MCQ 1. d 2. e 3. a 4. d 5. c Part 2: Question 2 A. The code in line 1 is valid. It creates a Mobile object without passing any parameter to the constructor, so the default value of 0 will be assigned to price. B. The code in line 2 will cause a compilation error, because the Mobile object m1 does not have its price variable initialized. We need to either pass a parameter to the constructor or set the price explicitly before printing. C. Mobile[] mobiles = new Mobile[2]; mobiles[0] = new

Uploaded by

malik8sabah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

‫ﺗﺟﻣﯾﻌﺎت اﻻﺧﺗﺑﺎرات اﻟﻧﺻﻔﯾﺔ‬ ‫‪2.

0‬‬
‫‪Rousol‬‬
‫‪M251 - MTA‬‬
‫‪Khadijah‬‬
‫‪Farah‬‬
‫‪Fatimah‬‬

‫ﺑﺴﻢ ﷲ اﻟﺮﺣﻤﻦ اﻟﺮﺣﯿﻢ‬

‫‪M251‬‬
‫ﺣِﻠﻒ اﻟﻄﻼب اﻟﻌﺼﺎﻣﯿﯿﻦ ﻳﻘﺪم ﻟﻜﻢ اﻟﻨﺴﺨﺔ اﻟﺜﺎﻟﺜﺔ ﻣﻦ ﺗﺠﻤﯿﻌﺎت اﻻﺧﺘﺒﺎرات اﻟﻨﺼﻔﯿﺔ ﻣﺤﻠﻮﻟ ً‬
‫ﺔ ﺑﺎﻟﻜﺎﻣﻞ‪.‬‬
‫ﺟﺪﻳﺪ اﻟﻨﺴﺨﺔ اﻟﺜﺎﻟﺜﺔ‪ :‬إﺿﺎﻓﺔ ﻧﻤﻮذج اﻟﻔﺼﻞ اﻟﺼﯿﻔﻲ ﻣﻦ ﻋﺎم )‪(22-23‬‬
‫وﺗﻌﻘﺐ وراﺟﻊ اﻟﻨﺴﺦ‪ ،‬وﻣَﻦ ﺟﻤﻊ اﻟﻤﻠﻔﺎت ﻋﻠﻰ ﻣﺮ اﻟﺴﻨﯿﻦ‪.‬‬ ‫ﱠ‬ ‫اﻟﺸﻜﺮ ُﻣﺴﺪى ﻟﻜﻞ ﻣﻦ ﺻﺤَﺢ‬
‫ُ‬
‫ﻧﺮﺟﻮ أﻻ ﺗﻜﻮن ھﺬه اﻟﺘﺠﻤﯿﻌﺎت ﻣﺤﻞ اﻋﺘﻤﺎدﻛﻢ ﻓﻲ اﻟﻤﺬاﻛﺮة‪ ،‬ﻓﺸﺮاﺋﺢ اﻟﻤﻘﺮر أوﻟﻰ وأﻛﺜﺮ أھﻤﯿﺔ‪.‬‬
‫ﻳﻐﻠﺐ ﻋﻠﻰ اﻟﻨﻤﺎذج ﺗﻜﺮار أﻓﻜﺎر اﻷﺳﺌﻠﺔ‪ ،‬ﻟﺬا ﻧﻨﺼﺢ ﺑﺎﻟﺮﺟﻮع إﻟﯿﮫﺎ واﻻھﺘﻤﺎم ﺑﮫﺎ‪.‬‬

‫ﻋﻼ‬
‫ﯾب ﻓﯾ ِﮫ و َ‬
‫ﻋ َ‬‫ﻓ َﺟ ﱠل َﻣن ﻻ َ‬ ‫ﺳ ﱠد اﻟ َﺧﻠَﻼ‬
‫ﻋﯾﺑًﺎ ﻓ ُ‬ ‫ْ‬
‫وإن ﺗ َ ِﺟ ْد َ‬

‫ﺣﺮر ﻓﻲ‪:‬‬
‫اﻟﻨﺴﺨﺔ اﻟﺜﺎﻟﺜﺔ )‪(3‬‬ ‫‪9/2/1445 – 25/8/2023‬‬
2022/2023 Summer
PART-2 ANSWERS

Q2.

1. access modifiers are the controlling levels of access to class members in Java. There are four main access
modifiers: public, protected, default, and private.

When an instance attribute variable is declared with a protected access modifier, it means that the variable
can be accessed by:

 The same class


 Classes in the same package
 Subclasses (even if they are in different packages)

2. A getter method (also called an 'accessor' method):

 It is used to access private attributes from outside the class where they were declared.
 A getter method should not change the state of the object.
 All private attributes should have getter methods.

A setter method (also called a 'mutator' method)

 It is one that changes the state of an object by setting the value of an instance variable.
 Setter methods do not normally return a value.

3.

 Is-a Relation (Inheritance): In Java, the "is-a" relationship is established using inheritance. If Class B
extends Class A, then it's said that Class B "is-a" Class A. Subclass (B) inherits the properties and
behaviors of the superclass (A).

 Has-a Relation (Composition): The "has-a" relationship is established through composition, where one
class contains an instance of another class as a member. This is often referred to as object composition.
For example, a Car "has-a" Engine.

4.
 Instance Variable: Also known as non-static variables, these belong to instances (objects) of a class.
Each object has its own copy of instance variables, and their values can be different for different
objects.

 Static Variable (Class Variable): These belong to the class itself, not to instances. They are shared
among all instances of the class. Changes made to static variables affect all instances of the class.
5.
 String: The ‘length()’ method is used for a ‘String’ object to get the number of characters (code units)
in the string.

 Array: The ‘length’ property is used for arrays to get the number of elements in the array. It provides
the size of the array.

Q3.

A.
Summer 22
9
M
U
-1

B.
Hi 1 r
Mi 3 g
Di 5 a
Zi 7 m
PART-3 ANSWER

Q1.

‫ ﻛﻼﺳﺎت ﻓﻲ اﻟﺒﺮوﺟﯿﻜﺖ ﺛﻢ اﻟﺼﻖ ﻣﺤﺘﻮى ﻛﻞ ﻛﻼس واﻵن ﺷﻐﻞ اﻟﺒﺮﻧﺎﻣﺞ‬3 ‫ ﻟﺘﺸﻐﯿﻞ اﻟﺒﺮﻧﺎﻣﺞ أﻧﺸﺊ‬:‫ﻣﻼﺣﻈﺔ‬

class Point {
private int x;
private int y;

public Point() {
this.x = 0;
this.y = 0;
}

public Point(int x, int y) {


this.x = x;
this.y = y;
}

public int getX() {


return x;
}

public void setX(int x) {


this.x = x;
}

public int getY() {


return y;
}

public void setY(int y) {


this.y = y;
}

@Override
public String toString() {
return "(" + x + ", " + y + ")";
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Point point = (Point) obj;
return x == point.x && y == point.y;
}

public double distanceTo(Point p) {


return Math.sqrt(Math.pow(x - p.x, 2) + Math.pow(y - p.y, 2));
}
}
Q2.

import java.util.ArrayList;

class Triangle {
ArrayList<Point> points;

public Triangle() {
points = new ArrayList<>(3);
points.add(new Point());
points.add(new Point());
points.add(new Point());
}

public double perimeter() {


double perimeter = 0;
perimeter += points.get(0).distanceTo(points.get(1));
perimeter += points.get(1).distanceTo(points.get(2));
perimeter += points.get(2).distanceTo(points.get(0));
return perimeter;
}

@Override
public String toString() {
return "Triangle with points: " + points.get(0) + ", " + points.get(1) + ", " + points.get(2) +
"\nPerimeter: " + perimeter();
}
}

Q3.

public class TestTriangle {


public static void main(String[] args) {
Point p1 = new Point(0, 6);
Point p2 = new Point(3, 0);
Point p3 = new Point(3, 4);

System.out.println("Are p1 and p3 in the same location? " + p1.equals(p3));

p1.setY(0);
p2.setX(6);

Triangle tri = new Triangle();


tri.points.set(0, p1);
tri.points.set(1, p2);
tri.points.set(2, p3);

System.out.println(tri.toString()); // Call toString() to print points and perimeter

}
}
2022/2023 Spring
Part 1 : MCQ [ 10 Marks ]: Each question carries a weight of 2 marks

Question 1: [10 marks] Read the following questions and choose the best answer.

1. Java is
a. interpreted b. object-oriented c. portable
d. All the above e. A and B only

2. _________ objects are mutable.


a. Array b. StringBuilder c. String
d. All the above e. A and B only

3. What is the output of the following code if s = "M251-MTA"?


System.out.println(s.contains ("MA"));
a. true b. false c. 5
d. 5, 7 e. -1

4. The behavior of an object is defined by a set of


a. methods b. instance variables c. class
variables
d. All the above e. A and B only

5. The class has no superclass.


a. System b. Math c. Object
d. All the above e. None of the above

Part 2 : Short Answer Questions [ 20 Marks ]

Question 2: [10 marks]


Consider the following code and then answer the questions below it.

public class Mobile( public class Test {


private double price; public static void main(String[] args) {
public Mobile(double p) { Mobile m1 = new Mobile(); // line 1
price = p; System.out.println(ml.price); // line 2
} // code lines
public double computeVAT() { }
return 0.14 * price; }
}
}

A. In the class Test, is the code in line 1 valid, or it will cause a compilation error? Explain.
B. In the class Test, is the code in line 2 valid, or it will cause a compilation error? Explain.
C. In the class Test, replace the comment "// code lines" with code implementing the
following requirements:
1. Declare and create an array of Mobile objects its size is 2.
2. Create two Mobile objects and assign them to the two elements of the array.
3. Using for loop, iterate over all Mobile objects of the array and print their VAT
Question 3: [10 marks]
Given the following main method. Do the following:
1. Declare and create an array list called weights which includes the following values: 79,92,65,
80.
2. Display on the screen the maximum wight by calling a built-in method.
3. Reverse the list.
4. Display on the screen the contents of the list after reversing.

import java.util.*;
public class CompleteCode {
public static void main(String[] args) {
//code
}

Part 3 : Problem Solving Questions [ 20 Marks ]

Question 4: [10 marks]


Consider the following code and then answer the questions below it.
Write the class Building which includes: (follow OOP principles you studied in the class) 1. two
attributes to store the address and number of floors of the Building.
2. a zero-arg constructor and a mutli-arg constructor.
3. getters and setters for the 2 attributes.
4. toString() method which overrides the Object's toString() method.

Question 5: [13 marks]


Write the class Hotel that inherits the class Building, and includes the following:
1. two attributes to store the name and star rating (a value from 1 to 5) of the Hotel.
2. A mutli-arg constructor which invokes the parent class constructor.
3. setter for the star rating attribute.
4. toString() method which invokes toString() method of the parent class.
5. equals() method which overrides the Object's equals() method. All attributes (including the
inherited ones) should be compared.

Question 6: [7 marks]
Write a Test class to test your classes by performing the following tasks:
1. Declare, create 2 Hotel objects and initialize them by valid values.
2. Print a message explaining if the 2 Hotels are identical or not.
3. Change star rating of the first Hotel to 5.
4. Display on the screen the address of the second Hotel.
5. Display on the screen all information of the first Hotel by calling no more than one
method.
PART-2 ANSWERS

Q2.

a. It’s invalid, because the class Mobile doesn’t have a zero-arg constructor.
b. It’s invalid, the attribute price is private; it can’t be accessed directly.
c.

Mobile[] mobiles = new Mobile[2];


mobiles[0] = new Mobile(1000);
mobiles[1] = new Mobile(2000);

for (Mobile mobile: mobiles) {


System.out.println(mobile.computeVAT());
}

Q3.

1.
ArrayList<Integer> weights = new ArrayList<>(Arrays.asList(79, 92, 65, 80));

2.
System.out.println(Collections.max(weights));

3.
Collections.reverse(weights);

4.
System.out.println(weights);
PART-3 ANSWERS

Q4.

// 1.
class Building {
private String address;
private int numberOfFloors;

// 2.
public Building() {}

public Building(String address, int numberOfFloors) {


this.address = address;
this.numberOfFloors = numberOfFloors;
}

// 3.
public String getAddress() {
return address;
}

public int getNumberOfFloors() {


return numberOfFloors;
}

public void setAddress(String address) {


this.address = address;
}

public void setNumberOfFloors(int numberOfFloors) {


this.numberOfFloors = numberOfFloors;
}

// 4.
@Override
public String toString() {
return "Building{" + "address=" + address + ", numberOfFloors=" + numberOfFloors + '}';
}
}
Q5.

// 1.
class Hotel extends Building {
private String name;
private int rating;

// 2.
public Hotel(String name, int rating, String address, int numberOfFloors) {
super(address, numberOfFloors);
this.name = name;
this.rating = rating;
}

// 3.
public void setRating(int rating) {
this.rating = rating;
}

// 4.
@Override
public String toString() {
return super.toString() + " Hotel{" + "name=" + name + ", rating=" + rating + '}';
}

// 5.
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Hotel other = (Hotel) obj;

return this.rating == other.rating &&


this.name.equals(other.name) &&
this.getAddress().equals(other.getAddress()) &&
this.getNumberOfFloors() == other.getNumberOfFloors();

}
}
Q6.

public class TestBuilding {

public static void main(String[] args) {

// 1.
Hotel h1 = new Hotel("Happy", 3, "D001", 10);
Hotel h2 = new Hotel("Wonder", 4, "D002", 15);

// 2.
System.out.println(h1.equals(h2));

// 3.
h1.setRating(5);

// 4.
System.out.println(h2.getAddress());

// 5.
System.out.println(h1.toString());
}
}
Fall 22-23
PART 1: MCQ [10 Marks]: Each question carries a weight of 2 marks
Read the following questions and choose the best answer.

1. Java is…………………. since Java programs are strictly checked by software before they run.

a. Robust b. secure c. portable d. interpreted e. dynamic

2. What is the value of the following expression?


"IT".compareTo("English");

a. 1 b. −1 c. 4 d. −4 e. true

3. In which relation if you delete the whole class, the part one will remain?

a. Inheritance b. Composition c. Aggregation d. has-a e. dynamic

4. The keyword …………. Is used to declare variables shared by all the instances of the class.
a. void b. final c. instance d. common e. static

5. The keyword…………. Could be used to call another constructor in the same class.

a. this b. this() c. self d. self() e. None of the above


PART 2: Short Answer Questions [20 Marks]

Question 1: [10 marks] Consider the following code and then answer the questions below it.

package page1 package page1

public class Circle { public class Test(

int radius; public static void main(String[] args) {

Circle c1 new Circle(); // line 1


}
System.out.println(c1.radius); // line 2

// code lines
}
}
A. In
line 1, is it valid to call Circle's constructor although you did not define it in the class Circle? Explain.
B. In line 2, is it valid to access the radius attribute directly. Explain.
C. Remove code lines and do the following:
1. declare and create an array of 2 Circles
2. Initialize the two elements of the array to refer to two Circles as in line 1
3. Using for loop, iterate over all Circles of the array and change their radii to 5.

Question 2: [10 marks]

Given the following main method. Do the following:

1. Declare and create an array list called salaries which includes the following values: 5000,
6000, 4000, 5500.

2. Display on the screen the highest salary by calling a method.

3. Sort the list.

4. Display on the screen the contents of the list after sorting.


import java.util.*;
public class CompleteCode(
}
public static void main(String[] args) {}
}
PART 3: Problem Solving Questions [30 Marks]
Question 1: [12 marks] Write the class PC which includes: ( follow OPP principles you studied in the
class)

1. Two attributes to store the brand (e.g. Dell, hp, etc.), and RAM size in GB (e.g. 8).
2. a zero-arg constructor and a multi-arg constructor.
3. getters and setters for the two attributes.
4. toString() method which overrides the Object's toString() method.

Question 2: [10 marks] Write the class Laptop that inherits the class PC, and include the following:

1. One attribute to know if the laptop has a touch screen or not.


2. A mutli-arg constructor which invokes the parent class constructor.
3. getters and setters for the new attribute.
4. toString() method which invokes the parent class toString() method.

Question 3: [10 marks] Write a Test class to test your classes by performing the following tasks:

1. Declare, create 2 Laptop objects and initialize them by valid values.


2. Change RAM size of the first laptop to 16.
3. Display on the screen the brand of the second laptop.
4. Display on the screen all information of the first laptop by calling no more than one method.
PART-2 ANSWERS

Q1

A. Yes, a defaulting contractor within an empty body is generated automatically.


B. Yes, it is valid because the radius is a default variable that can be used in any class in the
same package.

C.

public static void main(String[] args) {


Circle arr[] = new Circle[2]; //define the array

//define the object


arr[0] = new Circle();
arr[1] = new Circle();

//itrate over them to change the radius value


for (int i = 0; i <= arr.length; i++) {
arr[i].radius = 5;
}

Q2

public class CompleteCode {


public static void main(String[] args) {
// define the ArrayList
ArrayList < Integer > salary = new ArrayList < Integer > ();
// add the ArrayList element
salary.add(5000);
salary.add(6000);
salary.add(4000);
salary.add(5500);
// print the maximum element in the ArrayList
System.out.println(Collections.max(salary));
// sorting and print the ArrayList
Collections.sort(salary);
System.out.println(salary);
} //end main method
} // end class
PART-3 ANSWERS

Q1.

public class PC {

// define variables
private String brand;
private int RAM;
// define zero and multi constructors
public Pc(String name, int size) {
this.brand = name;
this.RAM = size;
}
public PC() {
this(null, 0);
}
//setters
public void setName(String name) {
this.brand = name;
}
public void setSize(int size) {
this.RAM = size;
}

// getters
public String getName() {
return this.brand;
}
public int getSize() {
return this.RAM;
}
@Override
public String toString() {
return " the breand name is :" + this.brand + " and the size is = " + this.RAM + " GB";
}
} //end class
Q2.

public class Labtop extends PC {

// define variable
private boolean isTouch;

// define zero and multi constructors


puclic Laptop(String name; int size; boolean state) {
super(name, size);
this.isTouch = state;
}

public Laptop() {
this(null, 0, false)
}

//setter and getter


public void setTouch(boolean state) {
this.isTouch = state;
}
public boolean isTouch() {
return isTouch;
}

public String toString() {


return super.toString() + " is it touch ?" + this.isTouch;
}
} //end class

Q3.

puclic class Test {


public static void main(String[] args) {
Laptop c1 = new Laptop("HP", 64, true); // define the first Laptop object
Laptop c2 = new Laptop("Lenovo", 32, false); // define the Second Laptop object
c1.setSize(16); // change c1 size
System.out.println(c2.getName()); //bring c2 name and display it
System.out.println(c1.toString()); // call toString() method to display all c1 information
} //end main method
} //end class
Fall 2019-2020
Part-I (MCQ): [10 marks: Each question carries a WEIGHT OF 2 marks]

(Read the following questions and choose the best answer. You should dedicate
approximately 10 minutes for this part.)

1. Which of the following correctly defines a queue?


a) A list of elements with a first in last out order.
b) A list of elements with a first in first out order.
c) Something that enables you to create a generic class without specifying a type
between angle brackets <>.
d) It is a keyword in Java that restricts the use of the code to local users only.

2. The instanceof operator works with …..


a) Class instances.
b) Primitive data types.
c) a and b.
d) None of the above.
3. Which of the following methods can be used to replace a segment in a string with a newstring?
a) remove(String oldString, String newString)
b) b) replaceAll(String oldString, String newString)
c) replaceAll(String newString)
d) substring(int start, int end, String newString)

4. Suppose that str1 and str2 are two strings. Which of the statements or expressions arevalid?
a) String str3 = str1 – str2;
b) str1 += str2;
c) str1 >= str2
d) b and c

5. A superclass’s members can be accessed in the super class


declaration and in subclass declarations.
a) Public
b) Private
c) protected
d) a and c
Part II: [20 marks] (This part consists of three questions; you have to answer all the questions inthis part.
You should dedicate approximately 30 minutes for this part.)
Question 1: [ 5 marks] What is the output of executing the following Java code?

class PartIIQ1
{
public static int f(int a, String s)
{ s =
"Java";
a=++a;
return
a;}
public static void test()
{ int n=10;
String s1 =
"Python";n =
f(n,s1);
System.out.println("n="+n+"\n
s1="+s1);String s2 = "Java";
String s3 = s2;
String s4 = new String("Java");
System.out.println(s2==s3);
System.out.println(s2==s4);
System.out.println(s2.equals(s4));
}
public static void main(String args[])
{ test();}
}
}
public static void main(String args[])
{ test();}
}
Question 2: [10marks] What is the output of executing the following Java code?

class B {

int a =50;

public void show() {


System.out.println("B show()");

}
public static void disp() {
System.out.println("B disp()");

class D extends B {

int a = 20;
public void show() {
System.out.println("D show()");
class E extends D {
} public void show()
{ super.show();
System.out.println("E
public static void disp()show()");
{ }
}
System.out.println("D disp()");
public class PartIIQ2 {
} static void DoPrint( B o )
public
{ o.show(); }
} public static void main(String[] args)

{ B x = new B();
B y = new D();
D z = new D();
E w = new E();
DoPrint(x);
DoPrint(y);
DoPrint(z);
DoPrint(w);
y.disp();
System.out.println(x.a);
System.out.println(y.a);
System.out.println(z.a);
System.out.println(w.a); }
}
Question 3: [ 5 marks] What is the output of executing the following Java code?

class Alpha

{ public String type = "a ";

public Alpha() { System.out.print("\nalpha "); }


public static void write()

{ System.out.println("Writing..."); }

}
public class Beta extends Alpha

{ public Beta() { System.out.print("beta "); }


void go()

{ type = "b ";

System.out.print(this.type + super.type); }
public static void write()

{ System.out.println("Writing code"); }
public
Part III: static
[30 marks] void
(This partmain(String[]
consists of three args)
questions; you have to answer all the
questions inthis part. You should dedicate approximately 60 minutes for this part.)
{ Alpha a = new Beta();
((Beta) a).go();
Question 1: a.write();
[8 marks] Implement a Java class named Movie that can be used with a video rental
business. The Movie class should contain the following:
}

}
1. A private String data field named title that stores the movie title.
2. A private integer data field year that stores the year of release.
3. A constructor that creates a movie with specified title and year.
4. The accessor functions for all data fields.
5. The mutator functions for all the data fields.
6. Override toString() to represent the movie object as a string.
7. A function calcLateFees() that takes as input the number of days a movie is late
and returns the late fee for that movie. The default late fee is $2/day.

Question 2: [7 marks] Implement a Java class named Comedy that is derived from Movie. The
Comedy class should contain the following:
1. A private integer data field rating that stores the user rating.
2. A constructor that creates a comedy object with specified title, year and rating.
3. Appropriate accessor and mutator methods.
4. A function that overrides toString() to represent the Comedy object as a string.
5. A overridden function calcLateFees() that takes as input the number of days a
movie is late and returns the late fee for that comedy object. The comedy late
fee is $3/day.

Question 3: [15 marks]

Implement a Java class named MovieTest that creates a function named


lateFeesOwed which receives an ArrayList of Movie objects, iterate thought it and
prompt the user to enter the number a movie is late to compute and return the
total amount of late fees. In your main function, create an ArrayList of Movie
objects named rentals, fills it with sample data of movie or comedy type objects.
Then, display all added data. Finally, call the function lateFeesOwed to find the
total amount of late fees and print the result in an appropriate message. For
example if you have added the following two objects in your main function,
 Movie(2011, “Norm of the North”)
 Comedy(2013, “Kung Fu Panda 3”, 5)

For 6 days late on rent, the output should be:

Year: 2011
Movie Title: Norm of the North

Year: 2013
Movie Title: Kung Fu Panda 3Rating: 5
Total late fee: $30.0

End of Questions
PART-2 ANSWERS

Q1.

n=11
s1=Python
true
false
true

Q2.

B show()
D show()
D show()
D show()
E show()
B disp()
50
50
20
20

Q3. alpha beta b b Writing...

PART-3 ANSWERS
Q1.
public class Movie {
private String title;
private int year;
public Movie(String title, int year) {
this.title = title;
this.year = year;
}
public String getTitle() {
return title;
}
public int getYear() {
return year;
}
public void setTitle(String title) {
this.title = title;
}
public void setYear(int year) {
this.year = year;
}
@Override
public String toString() {
return "title: " + title + ", year: " + year;
}
public int calcLateFees(int num) {
return 2 * num;
}
}
Q2.

public class Comedy extends Movie {


private int rating;
public Comedy(String t, int y, int rating) {
super(t, y);
this.rating = rating;
}
public int getRating() {
return rating;
}
public void setRating(int r) { this.rating = r;
}
@override
public String toString() {
return super.toString() + ", rating: " + rating;
}
@override
public int calcLateFees(int num) {
return 3 * num;
}
}

Q3.

public class MovieTest {

public int lateFeesOwed(ArrayList < Movie > movies) {


Scanner sc = new Scanner(System.in);
int total = 0;
for (Movie m: movies) {
System.out.print("Enter the number: ");
int num = sc.nextInt();
total += m.calcLateFees(num);
}
return total;
}
public static void main(String[] args) {
ArrayList < Movie > rentals = new ArrayList < > ();
rentals.add(new Movie(2011, "Norm of the North"); rentals.add(new Comedy(2013, "Kung Fu
Panda 3", 5);
for (Movie m: rentals) {
System.out.println(m);
int n = lateFeesOwed();
System.out.println("Total late fee: " + n);
}
}

}
Fall 2018-2019

Part 1 Multiple Choice Questions [10 marks]. Please choose one correct answer for each question.

1. Which of the following methods use to call moveTop() method that is found insuper-class?
a. this. moveTop(); b. moveTop();
c. super(moveTop() ); d. super.moveTop();

2. Which of these sentences is correct for declaring a primitive Boolean variable?a boolean
repeat==true; b. boolean repeat=false;
c. Boolean repeat=false; d. boolean[ ] repeat= boolean[4];

3. Which of these packages should be imported to work with ArrayLst in Java?


a. java.lang b. javax.swing c. java.io d. java.util

4. Which of the followings returns the number of characters in a String?


a. charAt() b. length() c. length d. indexOf()

5. When we say Java is............................. , it means that Java programs can run on different
platforms.
a. secure b. Robust c. Portable d. Threaded

6. One of the following data types could not be changed once it is created.

a.StringBuffer b. Stringbuilder c. double d. String

7. Which of the following return number of elements in an ArrayList object.


a. Length() b. size() c. size d. length

8. A ....................... is a data structure that holds data in a first in first out order.
a. Queue b. linkList c. Stack d. Array

9. A .................. method is used to insert elements in a stack data structure.


a. Pop() b. add() c. put() d. push()

10. The relationship between classes as shown below is ……….

a. Inheritance b. aggregation c. composition d. is-a


Part 2: Short Answer Questions [20 Marks]

Q1 [10 marks]

Use the code in figure 1 to answer the following questions.

public class Point2D { public class Point3D extends Point2D {


private int z;
private int x, y;
public Point3D() {
public Point2D() {
this.x = 0; super();
this.y = 0; this.z = 0;
} }
public Point3D(int x, int y, int z) {
public Point2D(int x, int y) {
super(x, y);
this.x = x;
this.z = z;
this.y = y;
} }

public int getX() { public int getZ() {


return this.x; return this.z;
}
}
public void setX(int x) { public void setZ(int z) {
this.x = x; this.z = z;
} }
public int getY() {
return this.y; public String toString() { return
} x + "," + Y + "," + z;
}
public void setY(int y) {
this.y = y; }
}
public String toString() { return
this.x + "," + this.y ;
}

}//end of class

A. Extract from the code in figure 1 the followings: [5 marks]


1. An instance method.
2. An overloading method.
3. An overriding method.
4. A key word that is used to call constructor of the parent class.
5. A key word that is used to represent inheritance relationship.
6. A key word that is used to refer to object itself.
7. An accessor method.
8. A mutator method.
9. A zero-argument constructor
10. A parent class

B. There are two syntax errors within toString() method in Point3D class. Find these errors
and explain why it happened. List three ways that you can correct the errors with [5 marks]
Q2 [10 marks]

Assume you have the following Java statements. int[]grades = {90,95,88,83, 88};

Write a single Java statement to convert grades array into gradeList of type ArrayList. [2 marks]

a. Write a single Java statement to printout the contents of gradeList. [1 mark]


b. Write a single Java statement to print out the index of first occurrence of grade
88. [1 mark]
c. Write a single Java statement to print out the maximum grade. [1 mark]
d. Write proper java statements to print out the average of gradeList. [5 marks]

PART-2 ANSWERS

Q1-A
1. getX()

2. Point2D(int x, int ty)

3. toString()

4. super

5. extends
6. this

7. getY()

8. setX(int x)

9. Point2D()

10. Point2D

Q1-B First error: x; it's not defined in this class second error: Y, it's not defined in this class

Three ways to correct:


1. super.getX() + "," + super.getY() + "," + z;
2. getX() + "," + getY() + "," + z;

3. make the variables protected in the super class, and change Y to y.

Q2
a. ArrayList<Integer>gradeList=new
ArrayList<>(Arrays.asList(grades));

b. System.out.println(gradeList);

c. System.out.println(gradeList.indexOf(88));

d. Collections.max(gradeList);

e.

int sum = 0;
for (int n: gradeList) {
sum += n;
}
System.out.println(1.0 * sum / gradeList.size());
Part 3 Problem Solving [ 30 Marks ]
P3.p[12 marks]

Write a Java program to develop a class Vehicle with the following specifications:

 The class has two protected attributes: maxSpeed, and maxPassengers of type
integer. [2 marks]

 The class has one private attribute: rideOn of type String. [0.5 mark]

 The class has three-argument constructor that sets the values of its instancevariables to
given values. [2 marks]

 The class has a zero-argument constructor that sets the values of its instancevariables to
its default values. It should invoke the three-argument constructor.
[2.5 marks]

 The class has public accessor and mutator methods for rideOn attribute. [3 marks]

 Override the Object’s toString() method in order to return a string


representation of the Vehicle status as: [2 marks]
Ride-On is: ….. , Maximum speed = : ….. , Maximum number of passengers = ……

P3.Q2 [12 marks]

Write a Java program to develop a class Car with the following specifications:

 Class Car inherits Vehicle class. [2 marks]


 The class has two private instance variables: model, and color of type String. [1 mark]
 The class has a multi-argument constructor that sets the value of its instancevariables to
given values. It should invoke its super-class constructor. [3 marks]

 Override the Object’s equals(Object) method in order to return a boolean value representing
whether two cars have the same values or not. [4 marks]
 Override the Object’s toString() method in order to return a string representation of the Car
instance variables as the below format, it should invoke its super-class toString() method:
[2 marks] Car Model is:……., Color is………, Ride-On is: ….. ,
Maximum speed =…………….. Maximum number of passengers = ……

P3.Q3 [6 marks]

Write a Java program to develop a class TestVehicle with a main method.Write the Java
statements in the main method that do the followings:

 Declare and create two objects of Car class: car1, and car2 with the followingvalues
consequently:

Car1 values: (Model: “Honda”, Color: “Blue”, rideOn: “surface”, Maximum Speed: 100,
MaxPassenegers: 4).
Car2 values: (Model: “Audi”, Color: “Red”, rideOn: “surface”, Maximum Speed: 100, Max
Passenegers: 5).

 Print out the status of each object.


 Print out whether car1 and car2 are equal or not.

End of Questions

PART-3 ANSWERS

Q1.

public class Vehicle {


protected int maxSpeed, maxPassengers;
private String rideOn;

public Vehicle(int speed, int passengers, String ride) {


this.maxSpeed = speed;
this.maxPassengers = passengers;
this.rideOn = ride;
}
public Vehicle() {
this(0, 0, "");
}
public String getRideOn() {
return this.rideOn;
}
public void setRideOn(String ride) {
this.rideOn = ride;
}
public String toString() {
return "Ride-On is: " + this.rideOn + " , Maximum speed = : " + this.maxSpeed + " , Maximum
number of passengers = " + this.maxPassengers;
}
}
Q2.

public class Car extends Vehicle {


private String model, color;

public Car(int speed, int passengers, String ride, String model, String color) {
super(speed, passengers, ride);
this.model = model;
this.color = color;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o == null) {
return false;
}
if (!(o instanceof Car)) {
return false;
}
Car other = (Car) o;
if (maxSpeed == other.maxSpeed && maxPassengers == other.maxPassengers &&
rideOn.equals(other.rideOn) && model.equals(other.model) && color.equals(other.color)) {
return true;
}

return false;
}
public String toString() {
return "Car Model is: " + model + ", Color is " + color + ", " + super.toString;
}
}

Q3.

public class TestVehicle {


public static void main(String[] args) {
Car car1 = new Car(100, 3, "surface", "Honda", "Blue");
Car car2 = new Car(100, 5, "surface", "Audi", "Red");
...
System.out.println(car1);
System.out.println(car2);
System.out.println(car1.equals(car2));
}
}
Fall 2018-2019 mkp

Part 1 Multiple Choice Questions [10 marks]. Please choose one correct answer for each question.

1. The current state of an object is represented by:


a. its protocol b. its class type
c. its behavior d. the values of its instance variables

2. The method that allows an object’s attributes values to be set or changed, is knownas an
method.
a. an accessor b. getter c. a mutator d. access modifier
3. A method that can be executed irrespective of whether any instances of the classhave been created
is known as ................................................... method:
a. instance b. class c. object d. none of the above
4. The return type of a constructor of a class is always:
a. void b. String c. integer d. it has no return type
5. A.......................is a data structure that holds data in a last in first out order.
a. Queue b. LinkedList c. Stack d. Array
6. How many String objects are created after all the statements below have beenexecuted?
String s1 = “Good Luck”;

String s2 = new String(“Good Luck”);String


s3 = s1;

a. 1 b. 2 c. 3 d. 4

7. Using the same Java statements in Q6, which of the following Java statements willhave false
result:
a. s1.equals(s3); b. s1==s2 c. s1.equals(s2); d. s1==s3

8. Which of the following Data type is immutable?


a. String b. StringBuffer c. StringBuilder d. int

9. One of the following types has a dynamic size.


a. ArrayList b. long c. int d. double

10. Which of the following return number of elements in an Array object?


a. Length() b. size() c. size d. length
Part 2 Short Answers [ 20 Marks ]

Part2.Q1 [10Marks]

Use the code in figure 1 to answer the following questions.


public class Shape
{ protected int x;
protected int y;
public Shape (int centerX, int centerY)
{ x = centerX; y = centerY; }
public String describe()
{ return "unknown shape with center " + x + ", "+y; }
}//end class Shape

public class Circle extends Shape


{ private int radius;
public Circle (int centerX, int centerY, int aRadius)
{ super(centerX, centerY);
radius = aRadius; }
public double getArea()
{ return Math.Pi * radius*radius;}public
String describe()
{ return "Circle with center " + x + "," + y + " and radius " +radius; }
}//end class Circle

a.How many classes are there in the above code? Give their names. [1 mark]
b. What are the attributes of the class Circle? [1 mark]
c. What kind of relationship is there between the classes? What Java keyword isused to
represent this kind of relationship? [1.5 marks]
d. What is the purpose of super(centerX, centerY)? [1.5 marks]
e. Define the meaning of overriding? Give an example of it from the above code. [2 marks]
f. Is the method describe() in the above classes considered as instance method, ora class
method? [1 mark]

g. What is the output of the below code when all lines have been executed one at atime.[1
mark]
Shape form = new Circle (10, 10, 5);
System.out.println ("form is " +
form.describe());
h. Given the above class definitions, is following statements valid in Java and why? [1 mark]
Shape s = new Circle(6,8,3);
Part2.Q2 [10Marks]
Assume you have the following Java statements.

String[] city={"London", "Paris", "Denver", "miami", "Tokyo"};

Write a single Java statement to represent each of the follwoings:

a. Convert city array into cityList of type ArrayList. [2 marks]


b. Printout the contents of cityList. [1 mark]
c. Store the cityList in reverse order. [1 mark]
d. Print the size of the cityList. [1 mark]
e. Print out if Miami is in cityList. [1 mark]
f. Add another city Paris to the list in location 4. [1 mark]
g. Print out the location of Denver in the list. [1 mark]
h. Remove the first occurrence of “Paris” from the list. [1 mark]
Rearrange cityList in random order.

Part 3 Problem Solving [ 30 Marks ]

Part3.Q1 [12 marks]

Write a Java program to develop a class Product with the following specifications:

 The class has three private attributes: code of type integer, description oftype String, and price of
type double.

 The class has three-argument constructor that sets the values of its instancevariables to given
values.
 The class has a zero-argument constructor that sets the values of its instancevariables to its
default values. It should invoke the three-argument constructor.
 The class has public accessor and mutator methods for price attribute.
 Override the Object’s toString() method in order to return a string
representation of the Product status as:
 Product Code is: ….. , description : ….. , and price = ……
Part3.Q2 [10 marks]

Write a Java program to develop a class Television with the following specifications:

 Class Television inherits Product class.


 The class has one private instance variables: name of type String.
 The class has a multi-argument constructor that sets the value of its instance variables to given
values. It should invoke its super-class constructor.
 The class has a public instance method getVateRate() that takes no argument and returns the vat
rate for a television which is 10% of television’s price.
 Override the Object’s equals(Object) method in order to return true if two televisions have the
same values.
 Override the Object’s toString() method in order to return a string representation of the Television
instance variables as the below format, it shouldinvoke its super-class toString() method:

 Product name is: ……., Product Code is: ….. , description : ….. , and price = ……

Part3.Q3 [8 marks]

Write a Java program to develop a class TestProduct with a main method. Writethe Java
statements in the main method that do the followings:

 Declare and create two objects of Television class: tv1, and tv2 with thefollowing values:
Tv1: (name = “TV”, code = 111, description = “Samsung”, price = 300),Tv2: (name
= “TV”, code = 222, description = “Soni”, price = 450).

 Print out the status of each object.


 Print out the vat rate of tv1.
 Modify the price of tv1 to be 600.
 Print out the vat rate of tv1.

End of Questions
PART-2 ANSWERS

Q1.

a. two classes: Shape, Circle

b. radius, x, y

c. inheritance, extends

d. to call the constructor of the super class.

e. the process of having two methods with same name but different body. an example: describe()

f. instance method

g. form is Circle with center 10, 10 and radius 5;

h. yes, we can assign a sub-class object to a super-class variable.

Q2.

a. ArrayList<String> cityList = new ArrayList<>


(Arrays.asList(city));

b. System.out.println(cityList);

c. Collections.reverse(cityList);

d. System.out.println(cityList.size());

e. System.out.println(cityList.contains(" Miami"));

f. cityList.add(4,"Paris");

g. System.out.println(cityList.indexOf(" Denver"));

h. cityList.remove("Paris");

i. Collections.shuffle(cityList);
PART-3 ANSWERS

Q1.

public class Product {


private int code;
private String description;
private double price;
public Product(int c, String d, double p) {
this.code = c;
this.description = d;
this.price = p;
}
public Product() {
this(0, "", 0.0);
}
public double getPrice() {
return this.price;
}
public void setPrice(double p) {
this.price = p;
}
public String toString() {
return "Product Code is: " + this.code + ", description : " + this.discription + ", and price =
" + this.price;
}
}

Q2.

class Television extends Product {


priavte String name;
public Television(int c, String d, double p, String n) {
super(c, d, p);
this.name = n;
}
public double getVateRate() {
return super.getPrice() * 0.1;
}
public boolean equals(Object o) {
if (o == null) { return false;
}
if (this == o) { return true;
}
if (!(o instanceof Television)) { return false
}
Television other = (Television) o;
return name.equals(other.name) && getPrice == other.getPrice();
}

public String toString() {


return "Product name is: " + name + ", " + super.toString();
}
}
Q3.

public class TestProduct {


public static void main(String[] args) {
Television tv1 = new Television(111, "Samsung", 300, "TV");
Television tv2 = new Television(222, "Soni", 450, "TV");
System.out.println(tv1);
System.out.println(tv2);
System.out.println(tv1.getVateRate());
tv1.setPrice(600);
System.out.println(tv1.getVateRate());
}
}
Spring 2018-2019

Part 1 [10 marks]

Determine whether each statement below is true or false

1. It is illegal to use private for any method in a subclass that overrides


a public method in super class. False

2. You must use a for-each loop, and not a traditional for loop, whenever
you need to iterate through ArrayList elements. False

3. Given a class with a class variable. All instances of this class get a
separate copy of the class variable. False

4. The == operator can be used to compare two String objects. The result
is always true if the two strings have the same content. False

5. The "switch" selection structure must end with the default case False

6. Each method in a class must have a unique name. False

7. A static method can be overridden. False

8. In an instance method or a constructor, this keyword is used to refer


to the current object. True

9. To avoid runtime errors, you must always specify the size of an array
when you declare it. False

10. Objects of a subclass can be assigned to a super class reference. True

Part2: [20 Marks]

Use the below code as shown in figure 1 to answer the following questions.

package MTA; package MTA;


public class TestMyParts{
public class MyParts {
public static int x = 7; public static void main(String[] args)
public int y = 3;
{
public static void increment()
{ x++;
MyParts a = new MyParts();
y++; }
public String toString(Object o) MyParts b = new MyParts();
{ return "x ="+ x+", ="+ y;}
}// end of MyParts }
}//end of class MyParts

Figure 1. Java Classes


1. Write the name (if any exist) of super class and sub class in figure1. Explainyour
answer. [2 marks]
2. Is it necessary to add setter and getter methods for attributes of MyParts?
Explain your answer. [2 marks]
3. Extract a compilation error in the above code. Explain the reason. [2 marks]
4. Extract an overridden method (if any exist). [1 mark]
5. Extract an overloaded method (if any exist). Explain your answer. [2 marks]
6. Extract all class members and instance members (if any exist). [2 marks]
7. Extract a java keyword that represents a class member. [1 mark]
8. Declare and create an ArrayList list1 of type MyParts. Add instances a and b
appear in figure 1 to list1. [2 marks]

9. Write a single Java statement to print out the elements of list1. [1 mark]
10. Is it valid to write list1.remove(); to delete all elements in list1. Correct itif it is
invalid.[2 marks]
11. What will be the output of following Java statements?
a. a.y = 5; b.y = 6;
b. a.x = 1; b.x = 2;
c. System.out.println("a.y = " + a.y);
d. System.out.println("b.y = " + b.y);
e. System.out.println("a.x = " + a.x);
f. System.out.println("b.x = " + b.x);
g. System.out.println("MyParts.x = " + MyParts.x);

Part3: Problem Solving [30 Marks]


Part3.Q1 [16 marks]

Write a Java program to develop a class Bicycle with the following specifications:
 The class has two private attributes of type integer: gear, and speed. [2 marks]
 The class has two-argument constructor that initilaises its attributes to given value. [2 marks]
 The class has a zero-argument constructor that intialises attributes to its defaultvalue.
It should invoke two-argument constructor in the same class. [2 marks]
 The class has public accessor and mutator methods for speed attribute. [4 marks]
 The class has a public applyBrake(int amount)that returns no value, and decrements speed
by amount value. [2 marks]
 The class has a public speedUp(int amount)that returns no value, and increments speedby
a mount value. [2 marks]
 Override the Object’s toString() method in order to return a string representation of the
Bicycle attributes values as: [2 marks]
Bicycle gear is: …………….., its speed = ………….…...
Part3.Q2 [8 marks]

Write a Java program to develop a class MountainBike with the following specifications:
 Class MountainBike inherits Bicycle class. [2 marks]
 The class has one private attribute: seatHeight of type integer. [0.5 mark]
 The class has a multi-argument constructor that sets the value of its attributes and the
inherited ones to given values. It should invoke its super-class constructor. [2.5 marks]
 Override the Object’s toString() method in order to return a string representation of the
MountainBike instance variables as the below format, it should invoke its super-class
toString() method: [3 marks]
Bicycle gear is: …………….., its speed = ………….…... , and seat height =…

Part3.Q3 [6 marks]

Write a Java program to develop a class TestBicycle with a main method. Write the Javastatements
in the main method that do the followings:

 Declare and create two objects mb1 and mb2 of MountainBike class with the following values

mb1 values: (gear: 4, speed = 200, seat height is 20).

mb2 values: (gear: 3, speed = 100, seat height is 25). [2 marks]


 Invoke applyBreak()with value 50 using mb1. [1 mark]
 Invoke speedUp()with value 100 using mb2. [1 mark]
 Invoke the proper method to print the status of two instances mb1and mb2 [2 marks]

PART-2 ANSWERS

Q1.

1. superclass: Object: by default because MyParts doesn't inherit any class explicitly.
supclass: MyParts

2. No, because there're are public.

3. y++; a static cannot access an instance variable


4. toString()

5. None

6. class members: x, increment()


instance members: y, toString()

7. static

8. ArrayList<MyParts> list1 = new ArrayList<>(); list1.add(a); list1.add(b);

9. System.out.println(list1);

10. No, correction: list1.clear();

11.
a. y=5
b. y=6
c. x=2
d. x=2
e. MyParts.x = 2

PART-3 ANSWERS

Q1.

public class Bicycle {


private int gear, speed;
public Bicycle(int gear, int speed) {
this.gear = gear;
this.speed = speed;
}
public Bicycle() {
this(0, 0);
}
public int getSpeed() {
return this.speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void applyBrake(int amount) {
this.speed -= amount;
}
public void speedUp(int amount) {
this.speed += amount;
}

public String toString() {


return "Bicycle gear is: "
this.gear + ", its speed = " + this.speed;
}
}

Q2.
public class MountainBike extends Bicycle {
private int seatHeight;

public MountainBike(int gear, int speed, int seatHeight) {


super(gear, speed);
this.seatHeight = seatHeight;
}

public String toString() {


return super.toString() + ", and seat height = " + this.seatHeight;
}
}

Q3.
public class TestBicycle {
public static void main(String[] args) {
MountainBike mb1 = new MountainBike(4, 200, 20);
MountainBike mb2 = new MountainBike(3, 100, 25);
mb1.applyBreak(50);
mb2.speedUp(100);
// or (mb1)
System.out.println(mb1.toString());
// or (mb2)
System.out.println(mb2.toString());
}
}
Spring 2018-2019 mkp

Part 1: [10 marks] Determine whether each statement below is true


or false.

1. In creating an array of objects, you have to instantiate the array object, andyou must instantiate
each element object that’s stored in the array. True

2. If you want a class you define to inherit methods from the Object class, youmust add extends
Object, to your class’s heading. False

3. If you wish to call a superclass method, you can use super.methodName(). True

4. The value of an array’s length equals the value of the array’s largest acceptable index.
False

5. In a UML diagram, # symbol represents a protected member. True

6. To avoid runtime errors, you must always specify the size of an ArrayList
when you declare it. False

7. It is legal to access a class member from an instance method and also from aconstructor. True

8. A class constant should be initialized within a constructor. False

9. It is illegal to directly access an instance member from a class method. True

10.A final class can be inherited. False


Part 2: [20 Marks]

Use the below code as shown in figure 1 to answer the following questions.

package MTA; package MTA;


public class MyClass { public class TestMyClass{
private int x; public static void main(String[] args)
public static int count; {
MyClass c1 = new MyClass(5);
public MyClass(int a)
{ x=a; count=0; } Myclass c2 = new MyClass(7);
public void setX(int a)
}
{ x = a; }
public int getX() }//end of class TestMyClass
{ return x; }
public static void incrementCount()
{ count++; }
public String toString()
{return this.x + "," + this.count ; }

}//end of class

Figure 1. Java Classes

1. What will be the output of following Java statements [3marks]

a. System.out.printLn(c1.getX()+","+c2.getX());
b. c2.incrementCount();
c. System.out.println(c1.toString ());
d. c1.incrementCount();
e. System.out.println(c2.toString());

2. Extract from the code in figure 1 the followings: [6 marks]


a. An accessor method.
b. A mutator method.
c. A class variable.
d. An overridden method.
e. An instance variable.
f. A class method.
g. An instance method.
h. A key word that is used to refer to object itself.
i. All access modifiers appear in MyClass, and explain its meaning.

3. Write a single Java statement to declare and create an array: array1 of MyClass that has
c1 and c2 as its elements. [2 marks]

4. Write a single Java statement to convert array1 into list1 of type ArrayList.
[2 marks]
5. In addition to using code in figure 1, use array1 and list1 you had already declared in
3 and 4 to state whether each of the following statements are validor invalid. Correct
the invalid ones. [7 marks]

a. MyClass.incrementCount();
b. MyClass.toString();
c. c1.setX(10);
d. System.out.println(array1);
e. array1[2] = new MyClass(2);
f. list1.put(c1);
g. System.out.println(list1.length);

Part3: Problem Solving [30 Marks]


Part3.Q1 [13 marks]

Write a Java program to develop a class BankAccount with the followingspecifications:


 The class has two private attributes: balance of type double, and owner of type
String. [2 marks]
 The class has two-argument constructor that initializes its attributes to given value.
[2 marks]
 The class has public accessor and mutator methods for balance attribute. [3 marks]
 The class has a public deposit(double amount) that returns no value, and
increments balance by amount value. [2 marks]
 The class has a public withdraw(double amount)that returns no value,
and decrements balance by a mount value. [2 marks]
 Override the Object’s toString() method in order to return a string
representation of the BanckAccout status as: [2 marks]
Owner is: ................., and balance= ..................$.
Part3.Q2 [11 marks]
Write a Java program to develop a class SavingAccount with the followingspecifications:

Class SavingAccount inherits BankAccount class. [2 marks]



The class has one private attribute: interestRate of type double. [0.5 mark]
 The class has a multi-argument constructor that sets the value of its attributes and the
inherited ones to given values. It should invoke its super-class constructor. [2.5 marks]
 The class has a public method addInterest() that takes no parameter and returns no value.
The method calculates a new local value interest which is =
balance*interestRate/100. Then it increments balance by interest value, it should
invoke its super-class deposit() method. [3 marks]
 Override the Object’s toString() method in order to return a string representation of
the SavingAccount instance variables as the below format, it should invoke its super-class
toString() method: [3 marks]
Owner is: …………….., balance= ………….…..$. Interest rate =.............................. $.
Part3.Q3 ........................................................................................................................ [6 marks]

Write a Java program to develop a class TestAccount with a main method. Write the Java
statements in the main method that do the followings:

 Declare and create an object of SavingAccount class: account1 with ownername “Ali”,
and balance = 2000$. [2 marks]
 Deposit amount 1000$ to balance of account1. [1 mark]
 Withdraw amount 500$ from balance of account1. [1 mark]
 Invoke addInterest() method using account1. [1 mark]
 Print out the status of account1. [1 mark]

End of Questions

PART-2 ANSWERS

Q1.

1.

a. 5,7
b. ------
c. 5,1
d. ------
e. 7,1

2.

a. getX()
b. setX()
c. count
d. toString()
e. x
f. incrementCount()
g. getX()
h. this
i. public: member is visible to any class
private: member is visible to the current class only.
3. Myclass[] array1 = {c1,c2};

4. ArrayList<MyClass> list1 = new ArrayList<>(Arrays.asList(array1));

5.

a. valid
b. invalid, c1.toString(); or c2.toString();
c. valid
d. valid, but should print list1 instead, or use a for loop.
e. invalid, array1[0]; or array1[1];
f. invalid, list1.add(c1);
g. invalid, list1.size();

PART-3 ANSWERS

Q1.

public class BankAccount {


private double balance;
private String owner;

public BankAccount(double b, String o) {


this.balance = b;
this.owner = o;
}
public double getBalance() {
return this.balance;
}
public void setBalance(double b) {
this.balance = b;
}

public void deposit(double amount) {


this.balance += amount;
}
public void withdraw(double amount) {
this.balance -= amount;
}
public String toString() {
return "Owner is: " + this.owner + ", and balance= " + this.balance + "$";
}
}
Q2.

public class SavingAccount extends BankAccount {


private double interestRate;

public SavingAccount(double balance, String owner, double rate) {


super(balance, owner);
this.interestRate = rate;
}
public void addInterest() {
double interest = super.getBalance() * this.interestRate / 100;
super.deposit(interest);
}
public String toString() {
return super.toString + " Interest rate = " + this.interestRate = " + this.interestRate + "
$.
";
}
}

Q3.

public class TestAccount {


public static void main(String[] args) {
SavingAccount account1 = new SavingAccount(2000, "Ali", 10);
account1.deposit(1000);
account1.withdraw(500);
account1.addInterest();
System.out.println(account1);
}
}
Summer 2018-2019

Part 1 [10 marks]


Determine whether each statement below is true or false. (1 mark each)

1. It is legal to use private for any method in a sub class that overrides
a public method in super class. False

2. It is legal to directly access an instance member from a class method. False

3. You can use a for-each loop, and not a traditional for loop, whenever
you need to iterate through ArrayList elements. False

4. Given a class with a class variable. All instances of this class share the
same copy of the class variable. True

5. A final class can be inherited. False

6. In a UML diagram, + symbol represents a private member. False

7. An immutable object is the one that upon creation its contents cannot be
changed. True

8. An instance method can be overridden. True

9. It is legal to directly access an instance member from a class method. False

10. You can specify the capacity of an ArrayList when you declare it True
Part 2: [20 Marks]

Use the below code as shown in figure 1 to answer the following questions.
package Mta; package Mta;
public class Worker { public class ActiveWorker extends Worker
private int id;
private String fullName; {
private static int counter; private boolean active;
public Worker(int aid, public ActiveWorker(){
String aName){ super(); active = false; }
id=aid; fullName= aName; public String toString(Object O){
counter++;}
public int getCounter(){ return "name is:" + fullName;}
return counter; } }// class
public String toString(){ package Mta;
return "name is:" + public class TestWorker {
fullName;} public static void main (String[] args)
}// class
{
Worker w11 = new Worker(11,"Ali");
System.out.println(w11.getCounter());
Worker w22 = new Worker(22,"Ahmad");
System.out.println(w11.getCounter());
System.out.println(w22.getCounter());
}
}// class

1. What is the output of the classes in figure 1. [3 marks]


2. Write a single Java statement to declare and create an array: array1 of Worker that
has w11 and w22 as its elements. [1 mark]

3. Write a single Java statement to convert array1 into list1 of type ArrayList. [2
marks]

4. Assume the following statements are written inside the main method
State whether each of the following is valid or invalid and explain your answer. [4 marks]

a. Worker w1 = new Worker();


b. System.out.println(Worker.counter);
c. ActiveWorker w2 = new ActiveWorker();
d. w2.toString();

5. Extract from the classes in figure 1 the following: [10 marks]


A. An accessor method.
B. A mutator method.
C. An instance method.
D. A class variable.
E. A parent class.
F. A child class.
G. A primitive type variable.
H. A reference type variable.
I. A overridden method.
J. A java keyword that is used to call a method from parent class.
K. An overloaded method.
L. A java keyword that is used to represent inheritance relationship.
M. An instance.
N. An instance variable.
O. Access modifiers appear in figure 1.
P. A java keyword that is used to call constructor of super class.

Part3: Problem Solving [30 Marks]


A- Develop a public class Circle to the following specifications: [10 marks]
 The class has a private instance variable, double radius.
 The class has a zero-argument constructor that sets the default value of radius
to1.0.
 The class has a one-argument constructor that sets radius to a given value.
 The class has the getter and setter methods for it instance variable radius.
 The class has a public method calcArea(). It has no argument and returns
thearea of the circle instance object using the following equation:
Area= π r2 where π= 3.14, use the Math class
 The class has to override Object’s toString() method in order to
return astring representation of the Circle instance variable and its
area as: Circle: Radius= 5.0 , The area= 78.54
B- Develop a public class Cone to the following specifications: [13 marks]

 The class inherits the Circle class.


 The class has one public instance variables double height
 The class has a zero-argument constructo that sets
thedefault value of height to 1.0.
 The class has a two-argument constructor that sets the values of height
andradius to given values. You should invoke the super-class one-
argument constructor for setting radius.
 The class has the getter and setter methods for its instance variable height.
 The class has a public method, calcVolume(),It has no argument and returns
the area of the cone instance object as a double value using the following
equation: Volume = 1/3 * base Area * height
 It has to use super-class’ method calcArea() to get the base area.
 The class has to overrides the Object’s toString() method in order to
returns astring consisting of a Circle’s radius, base area, Cone’s height,
and volume; such as: Circle : Radius= … , the area= … Cone: Height =
…, Volume=…….
C- Develop a public class TestMain to the following specifications: [7 marks]

 The class has the static main method


 The class has to declare an instance object of class Circle cr1, using
one-argument constructor; assign a suitable value for its radius.
 The class has to declare an instance object of class Cone co1, using
two-argument constructor; assign a suitable value for its radius and
height.
 The class has to declare an array of class Circle with 2 elements.
 The class has to fill the array with the 2 instance variables of the classes Circle and
Cone
 The class has to display the strings’ representation of the elements in the array.

End of Questions

PART-2 ANSWERS

Q1.

1. The code has errors, it will not run, but if you fix them the answer will be
1
2
2

2. Worker[] array1 = {w11,w22};

3. ArrayList<Worker> list1 = new ArrayList<> (Arrays.asList(array1));

4.
a. invalid, it doesn't have a zero-arg constructor
b. invalid, it's private *
c. invalid, as the superclass doesn't have a zero-arg constructor.

5.
a. getcounter()
b. ---
c. toString()
d. counter
e. Worker
f. ActiveWorker
g. id
h. fullName
i. toString()
j. super
k. toString(Object o)
l. extends
m. w11
n. id
o. public, private
p. super

PART-3 ANSWERS

Q1.

public class Circle {


private double radius;
public Circle() {
radius = 1.0;
}
public Circle(double r) {
radius = r;
}
public double getRadius() {
return radius;
}
public void setRadius(double r) { this.radius = r;
}
public double calcArea() {
return radius * radius * Math.PI;
}
@Override
public String toString() {
return "Circle: Radius= " + radius + " , The area= " + calcArea();
}
}
Q2.

public class Cone extends Circle {


public double height;
public Cone() { this.height = 1.0;
}
public Cone(double r, double h) {
super(r);
this.height = h;
}
public double getHeight() { return height;
}
public void setHeight(double h) { this.height = h;
}
public double calcVolume() { return 1 / 3.0 * super.getArea() * height;
}
@Override
public String toString() {
return super.toString() + " Cone: Height = " + height + " , Volume= " + calcVolume();
}
}

Q3.

public class TestMain {


public static void main(String[] args) {
Circle cr1 = new Circle(2.0);
Cone co1 = new Cone(3.0, 5.0);
Circle[] circles = new Circle[2];
circles[0] = cr1;
circles[1] = co1;
for (Circle c: circles) {
System.out.println(c);
}
}
}
Summer 2018-2019 makeup

Part 1 [10 marks]

Determine whether each statement below is true or false. (1mark each)

1. You can declare and create an ArrayList object using any primitive data type. False
2. The square notation [] is used to declare an ArrayList object. False
3. The ArrayList sizeOf() method returns the capacity of ArrayList object. False
4. In Java, the identifiers main, Main, and mAin are all distinct. True
5. A class cannot overload its constructors. False
6. If a subclass Sub overrides method m inherited from superclass Super,then m must
have the same signature in Sub and Super. .True
7. A programmer-defined class has no superclass unless the class isdefined
explicitly to extend a superclass. False
8. The operator = is used for assignment and initialization but not to testfor equality. .True
9. If the programmer fails to declare a local variable's data type, the typedefaults to int.
False
10. When you declare a constructor of a class as private, a syntaxerror will be
generated. False
Part 2: [20 Marks]
Use the below code as shown in figure 1 to answer the following questions.
package Mta; package Mta;

public class Robot { public class ColourRobot extends Robot


private int x, y; {
protected String color;
protected String name; public ColorRobot(){
public static int counter=0; super(); color = "red"; }
public String toString(Object O){ return
Public Robot() { super.toString()+ "\t color= "+
x=0; y=0; name=null; counter++;}
color; }
public Robot (int ax, int ay) {
}// class
x=ax; y=ay; name=null; counter++;}

public int getCounter(){


return counter;} package Mta;
public class TestRobot {
public void setName(String s){ public static void main (String[] args)
name = s;}
{
Robot teto = new Robot(2,3);
public String toString() { System.out.println(teto.getCounter());
return "{ X= " + x + "\t Y= "+ y+"\t ColorRobot deto = new ColorRobot();
Name= "+ name; } System.out.println(teto.getCounter());
}// class
System.out.println(deto.toString());
}

}// class

1. What is the output of the classes in figure 1. [4 marks]


2. Write another way to print out the value of counter variable in the main method.[2 marks]
3. Is it necessary to write setter and getter methods for attributes x, and y?Explain your
answer. [2 marks]
4. Is it necessary to write getCounter() method to return the value of
counterattribute? Explain your answer. [2 marks]

5. Is it valid to write the following statement inside the main method?Explain your answer. [2
marks]
ColorRobot arr = {teto, deto};

6. Extract from the classes in figure 1 the following: [8 marks]

1. An accessor method.
2. A mutator method.
3. An instance method.
4. A class variable.
5. A parent class.
6. A child class.
7. A primitive type variable.
8. A reference type variable.
9. An overridden method.
10. A java keyword that is used to call a method from parent class.
11. An overloaded method.
12. A java keyword that is used to represent inheritance relationship.
13. An instance.
14. An instance variable.
15. An Access modifier.
16. A java keyword that is used to call constructor of super class.

Part3: Problem Solving [30 Mark____________________


A: Develop a public class Employee according to the following specifications: [8 marks]

 The class has two private attributes integer id and string name. [2 marks]
 The class has a two-argument constructor that sets the value of its attributes to given
values. [2 marks]
 The class has a zero-argument constructor that sets the value of its attributes to the
default values. It should invoke its two-argument constructor. [2 marks]
 The class has to override Object’s toString() method in order to return a string
representation of the Employee object status such as: [2 marks]
Employee name:………… ID: …………………..

B: Develop a public class ContractEmp to the following specifications: [15 marks]

 The class inherits Employee class.


 The class has one private attribute integer hours. [2 marks]
 The class has a multi-argument constructor that sets the value of its attributes to given
values. It should invoke its two-argument super class constructor [2.5 marks]
 The class has the getter and setter methods for hours attribute. [2 marks]
 The class has a method calculateSalary(), that takes no argument and returns the salary of
the employee as: hours*40. [2 marks]
 Override the Object’s toString() method in order to return a string representation of the
ContractEmp attributes as the below format, it should invoke its super-class
toString() method: [3 marks]
Contract Employee name: …….. ID = …….. , hours=
…….

 The class has to override Object’s equals() method in order to return true ifthe object as
argument equal to the object who invoked the method and false otherwise. The method
should compare both the three instance variables of the two objects. [3.5 marks]
C: Develop a public class TestMain to the following specifications: [7 marks]

 The class has the static main method. [1 mark]


 Declare 2 instance variables of the class ContractEmp and assign their states by adding your
own values. [2 marks]
 Print the state of the above instance objects on screen. [2 marks]
 Check if the two instance objects are equal or not and print it on the screen. [2 marks]

End of Questions

PART-2 ANSWERS

Q1.

1.
1
2
{ X= 0 Y= 0 Name= null

2. Robot.counter

3. Yes, because they are private and can’t be accessed or modified outside the class

4. No, as it’s public

5. No, because we cannot assign a super-class value to a sub-class variable.

6.
a. getCounter()
b. setName()
c. toString()
d. counter
e. Robot
f. ColorRobot
g. x, y
h. name
i. toString(Object O)
j. super
k. toString()
l. extends
m. teto
n. x
o. public, protected
p. super

PART-3 ANSWERS

Q1.

public class Employee {


protected int id;
protected String name;

// two-argument constructor
public Employee(int i, String n) {
this.id = i;
this.name = n;
}

// zero-argument constructor
public Employee() {
this(0, ""); // invoke two-argument constructor
}

@Override // override Object's toString() method


public String toString() {
return "Employee name: " + name + " ID: " + id;
}
}

Q2.

public class ContractEmp extends Employee {


private int hours;

public ContractEmp(int id, String name, int hours) {


super(id, name);
this.hours = hours;
}

public int getHours() {


return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public double calculateSalary() {
return this.hours * 40;
}
@Override
public String toString() {
return "Contract Employee name: " + name + " ID = " + id + ", hours= " + this.hours;
}
@Override
public boolean equals(Object obj) {

if (this == obj)
return true;

if (obj == null || obj.getClass() != this.getClass())


return false;

ContractEmp emp = (ContractEmp) obj;


return (emp.name.equals(this.name) && emp.id == this.id && emp.hours == this.hours);
}
}

Q3.

public class PartTimeStud extends Student {


private int hours;
public PartTimeStud(int id, String name, int hours) {
super(id, name);
this.hours = hours;
}
public int getHours() {
return hours;
}

public void setHours(int hours) {


this.hours = hours;
}

@Override
public String toString() {
return "Part-Time Student: ID = " + getId() + ", Name = " + getName() + ", Hours = " + hours;
}
}
FIRST 2017-2018

Part 1: Multiple Choice Questions 16 marks - 1 mark for each correct answer.
20 minutes

1- In principles that underlie the Object-Oriented approach, the term allows us to focus on what
something does without considering the complexities of how it works.

a) Abstraction
b) Encapsulation
c) Generalisation/specialisation
d) Polymorphism

2- In UML class diagram, - sign beside the class member means:

a) Private
b) Public
c) Protected
d) N one o f th e abo ve

3- In UML class diagram, the relationships between the classes are shown by:

a) T ri angle s
b) C i r c l e s
c) B l a c k s
d) A r r o w s

4- In UML diagram, n Multiplicity means:

a) Exactly n
b) Excluding n
c) Zero or n
d) From zero to n

5- It is the idea passing down characteristics from parent to child, and plays an important part in
Object Oriented design and programming.

a) Abstraction
b) Polymorphism
c) Encapsulation
d) Inheritance

6- Each subclass can have its own constructor for

a) Specialised its attributes


b) Specialised initialization
c) Specialised its methods
d) All the above
Part2: Essay Questions [24 marks - 40 minutes]

Answer Four questions Only, each question is worth 6 marks

Q1- What is meant by Object-oriented programming? Provide example.

Q2- What is the difference between the UML and the methodology?

Q3- what information does the class diagram show?

Q4- What is meant by subclass object is substitutable in Object Oriented Programming?

Q5- What is encapsulation? How do you enforce encapsulation on instance variables? How
does sub-class access these instance variables?

Part 3: Problem-solving: 30 marks -60 minutes


Answer All the following questions.

Q1: 15 marks- 20 minutes

Using UML diagram; draw a Dependency association between two classes?

Specify its name and explain all the blocks and their contents in details.

Q3: [15 marks- 20 minutes]

A. Develop a public class Item to the following specifications: [7 marks]

 The class has two private instance variables: int itemCode, String itemName.
 The class has a multi-argument constructor that sets the values of its instance
variables to given values.
 The class has accessor and mutator methods for the instance
variables.
 Override the Object's toString() method in order to return a string representation of
the Item instance variables as:
ITEM: ItemCode: ,ItemName: ,

B. Develop a public class HardItem to the following specifications [8 marks]

 The class inherits Item class


 The class has two private instance variable string type and double price
 The class has a multi-argument constructor that sets the value of its instance
variables to given values. It should invoke its super-class constructor.
 Override the Object's toString() method in order to return a string representation of
the Item instance variables, it should invoke its super-class toString() method as:

ITEM: ItemCode: , ItemName: ,Type: , Price:

"End of the Questions”

PART-2 ANSWERS

Q1.

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects",


which can contain data and code that manipulates that data. OOP focuses on the objects that the
program is composed of, rather than the logic of the program itself.

A simple example of object-oriented programming is a program that simulates a dog. The program
would have a "Dog" class, with properties such as the dog's name and breed. The class would also
have methods such as "bark" and "wagTail" to show how the dog behaves. Each individual dog
would be an instance of the Dog class, with its own unique properties and methods.

Coding example:

class Dog {
private String name;
private String breed;
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
public void bark() {
System.out.println("Woof woof!");
}
public void wagTail() {
System.out.println("Tail wagging...");
}

public String getName() {


return name;
}

public String getBreed() {


return breed;
}
}
Q2. UML is a visual language for modeling software systems, while a methodology is a set of
practices for developing software. UML diagrams are used to communicate design within a chosen
methodology.

Q3. A class diagram in UML shows the classes and their relationships in a system. It includes class
names, attributes, methods, and visibility of class members. It also shows how many instances of
one class can be associated with one instance of another class.

Q4. a subclass object can be used in place of its superclass object without any problems. This is
because a subclass object has all the properties and behaviors of its superclass and may have
additional properties and behaviors.

Q5. Encapsulation is the practice of hiding an object's data and only allowing access through
methods. To enforce encapsulation, instance variables are made private, and can only be accessed
by subclasses through public or protected accessor and mutator methods.

PART-3 ANSWERS

Q1. A --> B «dependency»

Q2. This is a UML class diagram showing a dependency relationship between three classes:
Building, House, and RentCollector.

1. The Building class has a method called DetermineRent().


2. The House class also has a method called DetermineRent(), which is dependent on the
Building class's method.
3. The RentCollector class has a method called printBill().
The arrow pointing from House to Building and RentCollector to Building indicates that these classes
are dependent on the building class.
Q3 - A

public class Item {


private int itemCode;
private String itemName;
public Item(int itemCode, String itemName) {
this.itemCode = itemCode;
this.itemName = itemName;
}
public int getItemCode() {
return itemCode;
}
public void setItemCode(int itemCode) {
this.itemCode = itemCode;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
@Override
public String toString() {
return "ITEM: ItemCode: " + itemCode + ", ItemName: " + itemName;
}
}

Q3 - B

public class HardItem extends Item {


private String type;
private double price;

public HardItem(int itemCode, String itemName, String type, double price) {


super(itemCode, itemName);
this.type = type;
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "ITEM: ItemCode: " + super.getItemCode() + ", ItemName: " + super.getItemName() + ",
Type: " + type + ", Price: " + price;
}
}
Fall 2017-2018

Part 1: Multiple Choice Questions [6 marks] – 1 mark for eachcorrect answer, 20 minutes]

1- In principles that underlie the Object Oriented approach, the term that allows us to define
general characteristics and operations of an object and allows us to create more specialized
versions of this object.
a) Abstraction
b) Encapsulation
c) Generalization / specialization
d) Polymorphism

2- In UML class diagram, ~ sign beside the class member means:


a) Private
b) Public
c) Protected
d) Package

3- In UML class diagram, diverse types of arrow indicate for:


a) Overload relationships
b) Overlap relationships
c) Override relationships
d) Different relationships

4- In UML diagram, m.. n Multiplicity means:


a) Exactly m and n
b) Between m and n
c) Excluding m and n
d) None of the above

5- When all the characteristics from classes above a class in the hierarchy are
automatically featured in the below class is called
a) Inheritance
b) Polymorphism
c) Encapsulation
d) Abstraction

6- The initialize of the values for sub-class instance variables, are passed on to thesuper-class
constructor as:
a) Methods
b) Parameters
c) Relationship
d) Keywords
Part2: Essay Questions [24 marks - 40 minutes]

Answer Four questions Only, each question is worth 6 marks

Q1- What are the aims of Object Oriented programming paradigm?


Q2- What is the syntax of the attributes in UML diagram? Explain themeaning of each part
Q3- What is meant by Polymorphism in Object Oriented Programming?
Q4- What does instanceof operator used to in Object OrientedProgramming? And how
do we use it
Q5- What is an abstract class? How is it used?

Part 3: Problem solving: [30 marks -60 minutes]


Answer All the following questions
Q1: [5 marks- 20 minutes]
Using UML diagram; draw a Composition association between two classes?

Q2: [10 marks- 20 minutes]


Consider the following diagram

Assuming Publication is not an abstract type, decide which of the followingstatements are legal or not
legal and explain your answer.
a) Publication p = new Publication (. . .); p.recvNewlssue();
b) Publication p = new Magazine (. . .); p.recvNewlssue();
c) Publication p = new Magazine(. . .); p.sellCopy();
Q3: [15 marks- 20 minutes]

A. Develop a public class Student according to the following specifications: [7 marks]

 The class has two private instance variables integer id and string name.

 The class has a two-argument constructor that sets the value of itsinstance variables to
given values.
 The class has an accessor and mutator methods for the instancevariables.

B. Develop a public class PartTimeStud to the following specifications: [8marks]

 The class inherits Student class.


 The class has 1 private instance variable int hours.
 The class has a multi-argument constructor that sets the value ofits instance variables to
given values. It should invoke its two- argument super class constructor.
 Override the Object’s toString() method in order to return a string representationof the
partTimeStud instance variables, as:
Part-Time Student: ID = , Name= , Hours=

End of Questions

PART-2 ANSWERS

Q1.

Abstraction: OOP allows for the abstraction of real-world objects and their behaviors into reusable
software objects.

Encapsulation: OOP provides a way to hide the implementation details of an object and expose only
the necessary information through interfaces.

Inheritance: OOP enables the creation of new objects by inheriting characteristics from existing
objects.

Polymorphism: OOP allows objects to take on multiple forms depending on the context in which they
are used.

Reusability: OOP promotes code reuse by allowing objects to be defined and then used in multiple
contexts.

Modularity: OOP breaks down a complex system into smaller, more manageable units, making it
easier to understand and maintain.
Q2. In UML class diagrams, the syntax for attributes is as follows:

[visibility] [name] : [type] [multiplicity] [property string]

Visibility: This indicates the level of access to the attribute. It can be represented by + (public), -
(private), # (protected), or ~ (package).

Name: This is the name of the attribute.

Type: This is the data type of the attribute.

Multiplicity: This indicates the number of instances of the attribute. It is represented by a range, such
as 0..1, 1..*, or 3..5.

Property string: This is a list of properties that describe the attribute. It can include keywords such as
"readonly" or "static".

Q3. polymorphism refers to the ability of a single function or method to operate on multiple types
of data. This allows for a more flexible and reusable code, as a single function can be used to perform
the same operation on different types of objects.

Q4. It is used to determine whether an object is an instance of a particular class or interface. The
operator returns a boolean value indicating whether the object is of the specified type.
The syntax for using the instanceof operator is as follows:
object instanceof class

Q5. An abstract class is a class that cannot be instantiated. It is used as a base class for other
classes that implement the functionality declared by the abstract class. An abstract class can have
both abstract and non-abstract methods (abstract methods do not have a body, they are defined by
their signature only).

PART-3 ANSWERS

Q1.
Q2.

a) Publication p = new Publication(...); is a legal statement. This creates an object of the


Publication class and assigns it to the variable p.

b) Publication p = new Magazine(...); is a legal statement. This creates an object of the


Magazine class and assigns it to the variable p. Since Magazine is a subclass of Publication,
an object of the Magazine class can be assigned to a variable of the Publication class.

c) p.recvNewlssue(); and p.recvNewlssue(); are not legal statements. As per the given UML
diagram, the recvNewlssue() method is not defined in the Publication class or its subclasses.

d) p.sellCopy(); is a legal statement as per the given UML diagram, Publication class has
sellCopy() method and it can be invoked on object of Publication or its subclass Magazine.

Q3-A

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class RewriteCode {


public static void main(String[] args) {
int evenCount = 0;
int oddCount = 0;
try {
Scanner in = new Scanner(new File("test.txt"));
while ( in .hasNextLine()) {
int num = Integer.parseInt( in .nextLine());
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println("Even numbers: " + evenCount);
System.out.println("Odd numbers: " + oddCount);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
Q3-B

public class PartTimeStud extends Student {


private int hours;
public PartTimeStud(int id, String name, int hours) {
super(id, name);
this.hours = hours;
}
public int getHours() {
return hours;
}

public void setHours(int hours) {


this.hours = hours;
}
@Override
public String toString() {
return "Part-Time Student: ID = " + getId() + ", Name = " + getName() + ", Hours = " + hours;
}
}
Spring 2017-2018

Part 1 : Multiple choice Questions [ 10 Marks ]

1. Which of these words can be used to invoke a constructor in the sameclass?


a. super b. this c. extends d. void

2. Which of the following is used to declare constants in Java?


a. constant b. finally c. catch d. final

3. Variables that are declared inside a code block, and are valid only insidethat block are called
variables.
a. local b. instant c. static d. reference

4. What is the value of y after running this code?


int x=(int) 6.6; double y=x/4 + 1.3;

a. 2.8 b. 2.95 c. 2.3 d. 2

5. When we say Java is ………………, it means that Java programs are strictlychecked for errors before
they run.
a. secure b. Robust c. Portable d. Threaded

6. Which of the following data types occupies the largest size in memory?
a. char b. float c. int d. double

7. All class methods are specified in Java by using ....................................................keyword.


a. public b. static c. void d. final

8. Which of the following is an optional part of a try statement that is alwaysexecuted at the end of the
try statement?
a. finally b. catch c. throws d. all of them

9. Which of the following words is used to declare an exception in themethod header?


a. throws b. throw c. try d. all of them

10. Which of these classes is a root of the exception inheritance tree?


a. Exception b. EOFException c. Throwable d. IOEception
Part 2: [ 20 Marks ]

Part2.Q1 [10 marks]

Use the class diagram in figure 1 to answer the following questions:

1. State the relationship between class Circle and Cylinder class? What Java keyword is used
to represent this kind of relationship? [1 mark]
2. Extract two access modifiers symbols that are used in figure1. Write the Java keywords
that are used to represent each of them. Explain whateach of them mean.
[3 marks]
3. Write Java statements to implement the below constructor with its body.
+Circle(radius: double) [2 marks]

4. Extract from the class diagram in figure 1 the following: [4 marks]


 An accessor method.
 A mutator method.
 An override method.
 An example of overloading.
 A parent class.
 A child class.
 A primitive type variable.
 A reference type variable.
Part2.Q2 [10 marks]

Consider the following code:

/* 1…… proper import statements */ //2 marks

public class RewriteCode {


public static void main(String[] args)//2…….handle exception

Scanner in = //3………………… //2 marks

//4… any needed statements


while(in.hasNextLine())

Complete the missing code representing in the comments where theprogram should
do the followings:

Read integer numbers from a file named “test.txt” where each line of the filecontains
only one number. Print out how many odd and even numbers are there.

Part 3: [ 20 Marks ]

Part3.Q1 [12 marks]


Write a Java program to develop a class Person with the followingspecifications:

 The class has two private attributes: name, and id both of type String.

 The class has two-argument constructor that sets the values of its instance variables to
given values.
 The class has a zero-argument constructor that sets the values of its instance variables to
its default values. It should invoke the two- argument constructor.
 The class has public accessor and mutator methods for each attribute.
 Override the Object’s toString() method in order to return a string representation of the
Person status as:
Name is: , id is:
Part3.Q2 [10 marks]
Write a Java program to develop a class Student with the followingspecifications:

 Class Student inherits Person class.

 The class has four private instance variables: courseCode (of type
String), and grade1, grade2, and grade3 all of type int.

 The class has a multi-argument constructor that sets the value of its instance variables
to given values. It should invoke its super-class constructor.
 The class has a public calculateAverage() method that takes no arguments and
return the average of the three grades.

 Override the Object’s toString() method in order to return a string representation of the
Student instance variables as the below format, it should invoke its super-class
toString() method:
Name is: Id is: Module is: grades are: Average =

Part3.Q3 [8 marks]
Assume that you have a TestStudent class which has a main method, write the
following Java statements in the body of the main method.

 Declare and create an array of 2 elements of Student class.


 Fill the two items with an instance object of Student using multi-argument constructor.
 Print out the status of each element of the array.

End of Questions
PART-2 ANSWERS

Q1.

1. Inheritance relationship. Java keyword is extends.

2. +: public: it means the member is accessible anywhere outside the class.


-: private: it means the member is accessible only inside the class whereit is declared.

3. public Circle(double radius){


this.radius = radius; }

4.
 An accessor method. getRadius()
 A mutator method. setRadius() 
 An overid method. toString()
 An example of overloading. Circle(); Circle(radius: double)
 A parent class. Circle
 A child class. Cylinder
 A primitive type variable. radius or height
 A reference type variable. Color 

Q2.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class RewriteCode {


public static void main(String[] args) {
int evenCount = 0;
int oddCount = 0;
try {
Scanner in = new Scanner(new File("test.txt"));
while ( in .hasNextLine()) {
int num = Integer.parseInt( in .nextLine());
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println("Even numbers: " + evenCount);
System.out.println("Odd numbers: " + oddCount);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
PART-3 ANSWERS

Q1.

public class Person {


private String name;
private String id;

public Person(String name, String id) {


this.name = name;
this.id = id;
}

public Person() {
this("defaultName", "defaultId");
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

@Override
public String toString() {
return "Name is: " + name + ", id is: " + id;
}
}
Q2.

public class Student extends Person {


private String courseCode;
private int grade1, grade2, grade3;

public Student(String name, String id, String courseCode, int grade1, int grade2, int grade3) {
super(name, id);
this.courseCode = courseCode;
this.grade1 = grade1;
this.grade2 = grade2;
this.grade3 = grade3;
}

public Student() {
super();
}

public String getCourseCode() {


return courseCode;
}

public void setCourseCode(String courseCode) {


this.courseCode = courseCode;
}

public int getGrade1() {


return grade1;
}

public void setGrade1(int grade1) {


this.grade1 = grade1;
}

public int getGrade2() {


return grade2;
}

public void setGrade2(int grade2) {


this.grade2 = grade2;
}

public int getGrade3() {


return grade3;
}

public void setGrade3(int grade3) {


this.grade3 = grade3;
}

public double calculateAverage() {


return (grade1 + grade2 + grade3) / 3.0;
}

@Override
public String toString() {
return "Name is: " + super.getName() + " Id is: " + super.getId() + " Module is: " + courseCode
+ " grades are: " + grade1 + " " + grade2 + " " + grade3 + " Average = " + calculateAverage();
}
}
Q3.

public class TestStudent {


public static void main(String[] args) {
Student[] studentArray = new Student[2];
studentArray[0] = new Student("John Smith", "12345", "CSC101", 85, 90, 80);
studentArray[1] = new Student("Jane Doe", "67890", "CSC102", 80, 75, 70);

for (Student student: studentArray) {


System.out.println(student);
}
}
}
Summer 2017-2018

Part 1
Multiple Choice Questions [10 marks]. [2 marks each]

1. Which one of the following data types is a primitive data type in Java:
a. Array b. StringBuffer c. String d. long

2. The value of x after evaluating the following expression double x = 9.0/2.0 + 9/2 is:
a. 8.0 b. 9 c. 8.5 d. 9.0

3. Which of the following is used to declare and initialize an array in Java?


a. int numbers; b. int[ ] numbers= {1, 3, 4};
c. int numbers[ ]; d. int[ ] numbers = new int[3];

4. When s=”Egypt” , then the output from System.out.println(s.length()) is :


a. 5 b. 6
c. 4 d. the compiler gives run time error

5. When we say that Java allows a program to do several things at once this means that Java
is:
a. Secure b. interpreted c. threaded d. portable

6. Which of the following is an example of an unchecked exception?

a. EOFException c. IOException
b. MalformedURLException d. NullPointerException

7. Which of the following data types occupies the least amount of memory?
a. byte b. float c. int d. double

8. All class methods are specified in Java by using ......................................... keyword.


a. Public b. static c. void d. final

9. Which of the following is not a method of the Scanner class?


a. next() c. close()
b. hasNextBigDecimal () d. readLine()

10. The keyword needed to make use of library in a Java program is :


a. extends b. import c. interface d. final
Part 2: [20 Marks]
Use the code in figure 1 to answer the following questions. Note that: the
numbers in the code represent line’s numbers.

1 Package MTAtest 1 Package MTAtest


2 public class Point { 2 public class TestPoint2 {
3 private int x; 3 public static void main (String[]
4 public int y; args){

5 public Point() 4 Point p1;


6 {x=0;
7 y=0; } 5 Point p2= new Point();

8 public int feedback(){9 6 System.out.println(p1.y);


x=x+5;
10 return x; } 7 System.out.println(p2.x);

11 public double feedback( int s){ 8 System.out.println(p2.y);


12 x=x+s;
13 return (double) x; } 9 System.out.println(p2.toString());
10 }
14 public String toString() { 11 }
15 return x+ " " + y ; }
16 }
Figure 1 . Point Class

Q1. Use the class Test Point2 to answer the below question [16 marks]
a. Line 6: System.out.println(p1.y); is it legal? Explain your answer? [3 marks]
b. Line 7: System.out.println(p2.x); is it legal? Explain your answer? [3 marks]
c. Line 8: System.out.println(p2.y); is it legal? Explain your answer? [3 marks]
d. Is it legal to have both methods of feedback in the same Point class? What is this
feature called? Explain your answer. [3 marks]
e. Write a code that invokes the method feedback by using actual and formal
arguments, and using the p1 instance object. [4 marks]

Q2. Extract from the code in figure 1 the followings: [4 marks]

a. A constructor. b. An access modifier.


C. A primitive type variable. d. A reference type variable.
Part3: Problem Solving [30 Marks]

Part3.Q1 [10 marks]


Complete the missing code representing in the comments where:
Comment 1: proper import statements

Comment 2: ask the user to enter his/her name, and then saves this nameto a
text file c:\name.txt. Use try…catch statement to handle any exception of the type
Exception, and display a simple error message in case anexception happens.

//1………………………
public class RewriteCode {
public static void main(String[] args)
{
//2 ………………………………..
}
}

Part3.Q2 [20 marks]

Develop a Java program that includes the following classes:

A. A public class Animal that: [10 marks]


 has two private instance variables of the type String: name and action.
 has a one-argument constructor that sets name to a given value.
 has a setter method for action and a getter method for name.
 has a public method void move() which sets the value of action to"moving".
 overrides the Object’s toString() method in order to returns a stringconsisting of an
animal’s name and action; for example,
"Lucy is moving." (where "Lucy" is the animal’s name).
B. A public class Dog that: [10 marks]
 extends Animal class.
 has a public instance variable owner of type String.
 has a two-argument constructor that sets name and owner to givenvalues. You
should invoke the parent-class’ constructor.
 overrides the move() method in order to set action to "walking"whenever this
method is invoked.
 overrides the toString() method in order to returns a string consistingof a dog’s name,
action and owner similar to the following example,
"Lucy is walking. Lucy’s owner is Ali"
it should invoke its super-class toString() method.

End of questions
PART-2 ANSWERS

Q1.

1.
a. No, because it’s not a reference
b. No, x is private variable
c. Yes, it is legal. P2 is an instance object and y is public
d. Yes, it is legal to have both methods of feedback in the same Point class. This feature is called
polymorphism.
e. p1.feedback()  didn’t understand the requirements of the question

2.
a. Public point()
b. -------
c. x, y
d. p2
PART-3 ANSWERS

Q1.

1.

import java.io.FileWriter;
import java.util.Scanner;

2.
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name: ");
String name = scanner.nextLine();
try {
FileWriter fileWriter = new FileWriter("c:\\name.txt");
fileWriter.write(name);
fileWriter.close();
System.out.println("Name saved successfully!");
} catch (Exception e) {
System.out.println("An error occurred while saving the name.");
}

Q2.

a.

public class Animal {


private String name;
private String action;

public Animal(String name) {


this.name = name;
}

public void setAction(String action) {


this.action = action;
}

public String getName() {


return name;
}

public void move() {


this.action = "moving";
}

@Override
public String toString() {
return this.name + " is " + this.action + ".";
}
}
b.

public class Dog extends Animal {


public String owner;

public Dog(String name, String owner) {


super(name);
this.owner = owner;
}
@Override
public void move() {
action = "walking";
}
@Override
public String toString() {
return super.toString() + ". " + name + "'s owner is " + owner + ".";
}
}
Mock
Exams
2022/2023 Spring

Part-I (MCQ) [10 marks]:


1. What is the value of the following expression? 2+8/5*3
a) 6
b) 5
c) 2
d) 0.666666666667
e) none of the above
2. String str = “kitkat”.replace(‘k’,’a’)

In the above statement, the effect on the string kitkat is

a)The first occurrence of k is replaced by

b) All characters k are replaced by a.


c) All characters a are replaced by k.
d) Displays error message

3. Which statement is not true in java language?


a) A public member of a class can be accessed in all the packages.
b) A private member of a class cannot be accessed by the methods of the same class.
c) A private member of a class cannot be accessed from its derived class.
d) A protected member of a class can be accessed from its derived class.

4. A constructor ….
a) Must have the same name as the class it is declared within.
b) Is used to create objects.
c) May be declared private
d) d) (a), (b) and above.

5. An overloaded method could be …


a) The same method name with different types of parameters
b) The same method name with different number of parameters
c) The same method name and same number and type of parameters with different
return type
d) Both (a) and (b) above
Part II: [20 marks]

Question 1:

What is the output of executing the following Java code?

public class StringComparison{


public static void main(String args[]){
String str1 = new String("abc"); String
str2 = new String ("abc");
if (str1==str2) System.out.println("str1==str2 is
true");
else
System.out.println("str1==str2 is false");

if (str1.equals(str2)) System.out.println("str1.equals(str2) is
true");
else
System.out.println("str1.equals(str2) is false");

String str3="abc", str4 ="abc";if


(str3==str4)
System.out.println("str3==str4 is true");else
System.out.println("str3==str4 is false");

}
}

Question 2:
Given the following code:

public class Person{


public void talk(){
System.out.println("Hello");
}
}
public class Student extends Person{
public void talk(){
System.out.println("I am a student");
}
}

public class Test{


public static void main(String args[]){
Person p1 = new Person();
Person p2 = new Student();
Student s1 = new Student();
p1.talk();
p2.talk();
s1.talk();
}
}

1. What is the output of executing the following Java code?


2. Is it valid to write the following statement. Explain.
Student s2 = new Person();

Part III: [30 marks]

Question 1:
Implement a Java class named Sale that can be used for a simple sale of a single
item with no added discounts and no added charges. The Sale class should contain
the following:

1. A data field named item that stores the item name.


2. A data field price that stores the price of the item.
3. A constructor that creates a sale with specified item name and price.
4. The accessor functions for all data fields.
5. The mutator functions for all the data fields.
6. Override toString() to represent the sale object as a string.
7. A function bill() that returns the price for that item with no added discounts or charges.

Question 2:

Implement a Java class named DiscountSale that is derived from Sale. The
DiscountSale class should contain the following:
1. A data field discount that expressed as a percent of the price.
2. A constructor that creates a DiscountSale object with specified item, price and discount
values.
3. Appropriate accessor and mutator methods.
4. A function that overrides toString() to represent the DiscountSale object as a string.
5. A overridden function bill() that returns the net price for that DiscountSale object. Note:
net price = (1-discount/100)*price
Question 3:

Implement a Java class named SalesTest that creates a function named


totalBill() which receives an ArrayList of Sale objects, iterate thought it and
return the total bill for the list of items sold. In your main function, create an
ArrayList of Sale objects named sales, fill it with sample data of Sale or
DiscountSale type objects. Then, display all added data. Finally,
call the function totalBill() to find the total bill for the list of items sold and print
the result in an appropriate message.

For example, if you have added the following four objects in your main

function, Sale("Atomic coffee mug", 111.00);


Sale("Cup holder", 11.90);
DiscountSale("Floor mat", 10.90, 10);
DiscountSale("Map", 7.95, 0);

The output should be:

Atomic coffee mug, price = $111.0 and total cost = $111.0

Cup holder, price = $11.9 and total cost = $11.9

Floor mat, price = $10.9 and total cost = $9.81 (discount = 10.0%)

Map, price = $7.95 and total cost = $7.95 (discount = 0.0%)

Total bill = $140.66


PART-2 ANSWERS

Q1. The output is:

str1==str2 is false
str1.equals(str2) is truestr3==str4
is true

Q2. The Output is:

1.
Hello
I am a student
I am a student

2. No, it will cause a syntax error. Person objects are not always Students.

PART-3 ANSWERS

Solution provided by ISA

Q1.

// 1,2
class Sale {

private String item;


private double price;

// 3.
public Sale(String item, double price) {
this.item = item;
this.price = price;
}

// 4.
public String getItem() {
return item;
}

public double getPrice() {


return price;
}

// 5.
public void setItem(String item) {
this.item = item;
}
public void setPrice(double price) {
this.price = price;
}

// 6.
@Override
public String toString() {
return "Sale{" + "item=" + item + ", price=" + price + '}';
}

// 7.
double bill() {
return getPrice();
}
}

Q2.

// 1.
class DiscountSale extends Sale {

private double discount;

// 2.
public DiscountSale(double discount, String item, double price) {
super(item, price);
this.discount = discount;
}

// 3.
public double getDiscount() {
return discount;
}

public void setDiscount(double discount) {


this.discount = discount;
}

// 4.
@Override
public String toString() {
return super.toString() + "DiscountSale{" + "discount=" + discount + '}';
}

// 5.
@Override
double bill() {
return (1 - discount / 100) * getPrice();
}
}
Q3.

public class SalesTest {

public static double totalBill(ArrayList<Sale> sales) {


double result = 0;
for (Sale sale : sales) {
result += sale.bill();
}
return result;
}

public static void main(String[] args) {


ArrayList<Sale> sales = new ArrayList<>();
sales.addAll(Arrays.asList(
new Sale("Atomic coffee mug", 111.00),
new Sale("Cup holder", 11.90),
new DiscountSale("Floor mat", 10.90, 10),
new DiscountSale("Map", 7.95, 0)));

for (Sale sale : sales) {


System.out.println(sale.toString());
}

System.out.println(totalBill(sales));
}
}
Part 1
Multiple Choice Questions [10 marks]

1. Which of these words can be used to invoke a constructor in the sameclass?


a. super b. this c. extends d. void

2. Which of the following is used to declare constants in Java?


a. constant b. finally c. catch d. final

3. Variables that are declared inside a code block, and are valid only insidethat block are
called ......................................................... variables.
a. local b. instant c. static d. reference

4. What is the value of y after running this code?


int x=(int) 6.6; double y=x/4 + 1.3;

a. 2.8 b. 2.95 c. 2.3 d. 2

5. When we say Java is ………………, it means that Java programs are strictlychecked for errors
before they run.
a. secure b. Robust c. Portable d. Threaded

6. Which of the following data types occupies the largest size in memory?
a. char b. float c. int d. double

7. All class methods are specified in Java by using ......................................... keyword.


a. public b. static c. void d. final

8. Which of the following is an optional part of a try statement that is alwaysexecuted at the
end of the try statement?
a. finally b. catch c. throws d. all of them

9. Which of the following words is used to declare an exception in themethod


header?
a. throws b. throw c. try d. all of them

10. Which of these classes is a root of the exception inheritance tree?


a. Exception b. EOFException c. Throwable d. IOEception
Part 2: [20 Marks]

Part2.Q1 [10 marks]

Use the class diagram in figure 1 to answer the following questions:

Figure 1. A class diagram

2. State the relationship between class Circle and Cylinder class? What Java keyword is used to
represent this kind of relationship?[1 mark]

3. Extract two access modifiers symbols that are used in figure1. Write the Java keywords that
are used to represent each of them. Explain whateach of them mean. [3 marks]
[Award 1 mark for the symbol with its correct Java keyword. And another 1 mark formeaning of each.]

4. Write Java statements to implement the below constructor with its body.
+Circle(radius: double) [2 marks]

5. Extract from the class diagram in figure 1 the following: [4 marks] [0.5 mark for each]
 An accessor method. 
 A mutator method. 
 An overid method. 
 An example of overloading. 
 A parent class. 
 A child class. 
 A primitive type variable. 
 A reference type variable. 
Part2.Q2 [10 marks]

Consider the following code:

/* 1…… proper import statements */ //2 marks

public class RewriteCode {


public static void main(String[] args)//2…….handle exception

Scanner in = //3………………… //2 marks

//4… any needed statements


while(in.hasNextLine())

Complete the missing code representing in the comments where the


program should do the followings:

Read integer numbers from a file named “test.txt” where each line of the filecontains
only one number. Print out how many odd and even numbers are there.

Part3: Problem Solving [30 Marks]

Part3.Q1 [12 marks]


Write a Java program to develop a class Person with the followingspecifications:

 The class has two private attributes: name, and id both of type String.

 The class has two-argument constructor that sets the values of its instance variables to
given values.
 The class has a zero-argument constructor that sets the values of its instance variables to
its default values. It should invoke the two- argument constructor.
 The class has public accessor and mutator methods for each attribute.
 Override the Object’s toString() method in order to return a string representation of the
Person status as:
Name is: , id is:
Part3.Q2 [10 marks]
Write a Java program to develop a class Student with the followingspecifications:

 Class Student inherits Person class.

 The class has four private instance variables: courseCode (of type
String), and grade1, grade2, and grade3 all of type int.

 The class has a multi-argument constructor that sets the value of its instance variables to
given values. It should invoke its super-class constructor.
 The class has a public calculateAverage() method that takes no arguments and
return the average of the three grades.

 Override the Object’s toString() method in order to return a string representation of the
Student instance variables as the below format, it should invoke its super-class toString()
method:
Name is: Id is: Module is: grades are: Average =

Part3.Q3 [8 marks]
You are required to write the following codes in the body of the class
TestStudent:

 Declare and create an array of 2 elements of Student class.


 Fill the two items with an instance object of Student using multi-argument constructor.
 Print out the status of each element of the array.
PART-2 ANSWERS

Q1.

5. Inheritance relationship. Java keyword is extends.

6. +: public: it means the member is accessible anywhere outside the class.


-: private: it means the member is accessible only inside the class whereit is declared.

7. public Circle(double radius){


this.radius = radius; }

8.
 An accessor method. getRadius() or any get method in figure
 A mutator method. setRadius() or any set method in figure 1.
 An overid method. toString()
 An example of overloading. Circle(); Circle(radius: double) //accept any correct
example
 A parent class. Circle
 A child class. Cylinder
 A primitive type variable. radius or height
 A reference type variable. Color

Q2.

import java.io.*; //1 mark


import java.util.*;
public class RewriteCode {
//1 mark
public static void main(String[] args) throws IOException { //2 mark
Scanner in = new Scanner(new File("C:/test.txt"));
int co = 0, ce = 0; // 1 mark while(in.hasNextLine())

if ( in .nextInt() % 2 == 1) //2 marks co++; //0.5 mark


else
ce++; //0.5 mark

System.out.println("number of odd numbers = " + co +


" number of even numbers = " + ce); //1 mark

in .close(); // 1 mark
}
}
PART-3 ANSWERS

Q1.

public class Person { //1 mark


private String name, id; //1 mark

public Person(String a, String b) { //2 marks name = a


id = b;
}

public Person() { }; //2 mark this(null, null)

public void setName(String a) { }; //1 mark name =a

public void setId(String b) { }; // 1 mark id = b

public String getName() { }; // 1 mark return name

public String getId() { }; // 1 mark return id

public String toString() { }; // 2 marks return "Name: "+ name+"\t Id:"+id


}

Q2.

public class Student extends Person { //2 marks private String courseCode;
private int grade1, grade2, grade3;

public Student(String n, String d, String c,


int g1, int g2, int g3) { //1 mark super(n,d); // 1 mark
courseCode = c; // 1 mark

grade1 = g1;
grade2 = g2;
grade3 = g3;

public double calculateAverage() { //2 marks return (grade1+grade2+grade3)/3.0;


}

public String toString() { // 3 marks return super.toString()+" Course code:"+ courseCode+


" grades are:" + grade1 + " " + grade2 + ", " + grade3 + " average =" + calculateAverage();
}
}

Q3.

public class JavaApplication2 {

public static void main(String[] args) { //1 mark Student[] st = new Student[2]; //2 mark
st[0] = new Student("Ali", "111", "M251", 77, 80, 90); //1.5 mark st[1] = new
Student("Ahmad","222","M251",88,92,90); // 1.5 mark System.out.println(st[0].toString());
//1 mark System.out.println(st[1].toString()); // 1 mark
}
}
Part 1 [10 marks]

Multiple Choice Questions OR T/F questions

1. Which of those Java editions is intended for large-scale systems?


a. JVM b. J2ME c. J2EE d. J2SE

2. The method that allows an object’s attributes values to be set or changed, is


known as an
………………… method.
a. an accessor b. getter c. a mutator d. access
modifier
3. A method that can be executed irrespective of whether any instances of
the class have beencreated is known as ……… method:
a. instance b. class c. object d. none of
the above

4. A................... is a data structure that holds data in a first in first out order.
a. Queue b. linked-List c. Stack d. Array
5. How many String objects are created after all the statements below have
been executed?String s1 = “Welcome to Java”;
String s2 =
“Welcome to Java”;
String s3 = s1;

a. 1 b. 2 c. 3 d. 4

OR: Say if the below statements are T/f:


1. The term "default constructor" is applied to the first constructor written
by theauthor of a class. False
2. The public access specifier for a field indicates that the attribute may
not beaccessed by statements outside the class. False
3. Instance methods do not have the key word static in their headers. True
Part 2: [20 marks]

Part2.Q1 Check the code in figure 1 and then answer the following
questions.

package Q1;

public class Animal {


public void move()
{
System.out.println("Animals can move"); }
}// class

package Q1;
public class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run"); }
public void bark() {
System.out.println("Dogs can bark"); }
public void doAll(){
super.move();
move();
bark(); }
}//class

Figure 1. Java code

A. Extract from the code in figure 1 the followings:


1. An instance method.
2. An overriding method.
3. A key word that is used to call a method of the parent class.
4. A key word that is used to represent inheritance relationship.
5. A parent class.
6. A sub class.
7. An access modifier. Explain its meaning.
Part2.Q2
int[] x = {4,52,8,3};

ArrayList<Integer> list1 = new ArrayList<Intgere>();

Say whether or not the following statements are valid or invalid. Correct the
invalid ones.

a. System.out.println(x);
b. System.out.prinltn(list1);
c. System.out.println(x.size());

Part3: Problem Solving [30 Marks]

Part3.Q1
Develop a public class Employee according to the following
specifications:

 The class has two private instance variables integer id and string name.
 The class has a two-argument constructor that sets the value of its
instance variables to given values.
 The class has a zero-argument constructor that sets the value of its instance
variables to the default values. It should invoke its two- argument
constructor.
 The class has the getter and setter methods for its instance variables.
 Override the Object’s toString() method in order to return a string representation
of the Employee status as:
ID = , Name=
Part3.Q2

Develop a public class ContractEmp to the following specifications:

 The class inherits Employee class.


 The class has one private instance variable int days.
 The class has a multi-argument constructor that sets the value of its
instance variables to given values. It should invoke its two-argument super
class constructor.
 Override the Object’s toString() method in order to return a string
representation of the ContractEmp instance variables as the below format, it
should invoke its super-class toString() method:

Contract Employee: ID = , Name= , Days=

 The class has to override Object’s equals() method in order to return true if
the object as argument equal to the object who invoked the method and
falseotherwise. The method should compare both the three instance
variables of the two objects.

Part3.Q2

In the Test class which includes a main method, you are


required to write thefollowing codes:

 Declare 2 objects of the class ContractEmp and assign their states by adding
your own values.
 Print the state of the above instance objects on screen.
 Check if the two instance objects are equal or not and print it on
thescreen.
PART-2 ANSWERS

Q1.

1. Any method from figure


2. move()
3. Super.move()
4. extends

5. Animal

6. Dog
7. Public: the member is accessible anywhere.

Q2.
a. System.out.println(x);
//invalid it should use for loop:

// for(int i=0; i<x.length; i++) System.out.println(x.length);

b. System.out.prinltn(list1); //valid

c. System.out.println(x.size());
//invalid it should be list1.size(), or x.length;

PART-3 ANSWERS

Q1.

public class Employee {


private int id;
private String name;

public Employee(int aid, String aname) {


id = aid;
name = aname;
}
public Employee() { this(0, null);
}

public int getId() { return id;


}
public void setId(int aid) {
id = aid;
}

public String getName() {


return name;
}
public void setName(String aname) {
name = aname;
}

public String toString() {


return " Contract Employee: ID =" + getId() + ",\t Name=" + getName();
}
}

Q2.

public class ContractEmp extends Employee {


private int days;

public ContractEmp(int aid, String aname, int adays) {


super(aid, aname);
days = adays;
}

public String toString() {


return super.toString() + ",\t Days=" + days;
}

public boolean equals(Object obj) {


ContractEmp tt = (ContractEmp) obj;
return ((days == tt.days) && (getId() == tt.getId()) &&
(getName().equals(tt.getName())))
}
} //class

Q3.

public class Test {


public static void main(String[] args) {
ContractEmp p1 = new ContractEmp(1, "Ali hassan", 8);
ContractEmp p2 = new ContractEmp(2, "Noor Ali", 5);
System.out.println(p1.toString() + "\n" + p2.toString());
System.out.println(p1.equals(p2));
System.out.println(p2.equals(p1) //Or
}
} //class
Scan or Click Me

You might also like