Inheritance in Java: Access Modifiers
Inheritance in Java: Access Modifiers
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:
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.
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;
}
@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;
}
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());
}
@Override
public String toString() {
return "Triangle with points: " + points.get(0) + ", " + points.get(1) + ", " + points.get(2) +
"\nPerimeter: " + perimeter();
}
}
Q3.
p1.setY(0);
p2.setX(6);
}
}
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
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
}
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.
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() {}
// 3.
public String getAddress() {
return address;
}
// 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;
}
}
Q6.
// 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. 1 b. −1 c. 4 d. −4 e. true
3. In which relation if you delete the whole class, the part one will remain?
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.
Question 1: [10 marks] Consider the following code and then answer the questions below it.
// 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.
1. Declare and create an array list called salaries which includes the following values: 5000,
6000, 4000, 5500.
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:
Question 3: [10 marks] Write a Test class to test your classes by performing the following tasks:
Q1
C.
Q2
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.
// define variable
private boolean isTouch;
public Laptop() {
this(null, 0, false)
}
Q3.
(Read the following questions and choose the best answer. You should dedicate
approximately 10 minutes for this part.)
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
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 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
{ System.out.println("Writing..."); }
}
public class Beta extends Alpha
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.
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
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.
Q3.
}
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];
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.
8. A ....................... is a data structure that holds data in a first in first out order.
a. Queue b. linkList c. Stack d. Array
Q1 [10 marks]
}//end of 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]
PART-2 ANSWERS
Q1-A
1. getX()
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
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]
Write a Java program to develop a class Car with the following specifications:
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).
End of Questions
PART-3 ANSWERS
Q1.
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.
Part 1 Multiple Choice Questions [10 marks]. Please choose one correct answer for each question.
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”;
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
Part2.Q1 [10Marks]
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.
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:
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).
End of Questions
PART-2 ANSWERS
Q1.
b. radius, x, y
c. inheritance, extends
e. the process of having two methods with same name but different body. an example: describe()
f. instance method
Q2.
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.
Q2.
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
9. To avoid runtime errors, you must always specify the size of an array
when you declare it. False
Use the below code as shown in figure 1 to answer the following questions.
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);
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
PART-2 ANSWERS
Q1.
1. superclass: Object: by default because MyParts doesn't inherit any class explicitly.
supclass: MyParts
5. None
7. static
9. System.out.println(list1);
11.
a. y=5
b. y=6
c. x=2
d. x=2
e. MyParts.x = 2
PART-3 ANSWERS
Q1.
Q2.
public class MountainBike extends Bicycle {
private int 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
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
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
Use the below code as shown in figure 1 to answer the following questions.
}//end of class
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());
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);
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};
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.
Q3.
1. It is legal to use private for any method in a sub class that overrides
a public method in super class. 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
7. An immutable object is the one that upon creation its contents cannot be
changed. True
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
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]
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
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.
Q3.
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;
}// class
5. Is it valid to write the following statement inside the main method?Explain your answer. [2
marks]
ColorRobot arr = {teto, deto};
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.
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: …………………..
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]
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
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.
// 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
}
Q2.
if (this == obj)
return true;
Q3.
@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
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
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
Q2- What is the difference between the UML and the methodology?
Q5- What is encapsulation? How do you enforce encapsulation on instance variables? How
does sub-class access these instance variables?
Specify its name and explain all the blocks and their contents in details.
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: ,
PART-2 ANSWERS
Q1.
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...");
}
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
Q2. This is a UML class diagram showing a dependency relationship between three classes:
Building, House, and RentCollector.
Q3 - B
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
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]
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]
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.
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: This indicates the level of access to the attribute. It can be represented by + (public), -
(private), # (protected), or ~ (package).
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.
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;
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
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
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
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]
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 ]
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:
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.
End of Questions
PART-2 ANSWERS
Q1.
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;
Q1.
public Person() {
this("defaultName", "defaultId");
}
@Override
public String toString() {
return "Name is: " + name + ", id is: " + id;
}
}
Q2.
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();
}
@Override
public String toString() {
return "Name is: " + super.getName() + " Id is: " + super.getId() + " Module is: " + courseCode
+ " grades are: " + grade1 + " " + grade2 + " " + grade3 + " Average = " + calculateAverage();
}
}
Q3.
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
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
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
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]
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 ………………………………..
}
}
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.
@Override
public String toString() {
return this.name + " is " + this.action + ".";
}
}
b.
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.
Question 1:
if (str1.equals(str2)) System.out.println("str1.equals(str2) is
true");
else
System.out.println("str1.equals(str2) is false");
}
}
Question 2:
Given the following code:
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:
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:
For example, if you have added the following four objects in your main
Floor mat, price = $10.9 and total cost = $9.81 (discount = 10.0%)
str1==str2 is false
str1.equals(str2) is truestr3==str4
is true
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
Q1.
// 1,2
class Sale {
// 3.
public Sale(String item, double price) {
this.item = item;
this.price = price;
}
// 4.
public String getItem() {
return item;
}
// 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 {
// 2.
public DiscountSale(double discount, String item, double price) {
super(item, price);
this.discount = discount;
}
// 3.
public double getDiscount() {
return discount;
}
// 4.
@Override
public String toString() {
return super.toString() + "DiscountSale{" + "discount=" + discount + '}';
}
// 5.
@Override
double bill() {
return (1 - discount / 100) * getPrice();
}
}
Q3.
System.out.println(totalBill(sales));
}
}
Part 1
Multiple Choice Questions [10 marks]
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
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
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
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]
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.
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:
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:
Q1.
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.
in .close(); // 1 mark
}
}
PART-3 ANSWERS
Q1.
Q2.
public class Student extends Person { //2 marks private String courseCode;
private int grade1, grade2, grade3;
grade1 = g1;
grade2 = g2;
grade3 = g3;
Q3.
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]
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
Part2.Q1 Check the code in figure 1 and then answer the following
questions.
package Q1;
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
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.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
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
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.
5. Animal
6. Dog
7. Public: the member is accessible anywhere.
Q2.
a. System.out.println(x);
//invalid it should use for loop:
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.
Q2.
Q3.