Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

COMP2150 Quiz2 (Constructor(), and Polymorphism) (Maximum: 74 points) Names: (pr

ID: 3755049 • Letter: C

Question

COMP2150 Quiz2 (Constructor(), and Polymorphism) (Maximum: 74 points) Names: (print your name here) Sept 26, 2018/Sept 27, 2018 (1) (3 points) What is a reference variable in association to a class type? (Describe with java code with explanation) (2) (3 points) Reference Variables can be polymorphic. What does that mean? (Describe with java code with explanation) (3) (5 points) How many Strings objects are instantiated by the following code segment: String s1, output; s1 "hello" output-" The string reversed is: " for (int i sl.length()-1; >:0; i-) output +# s1.charAt(i) + " " ; A. 1 B. 4 C. 5 D. 7 (Cycle the answer)

Explanation / Answer

1) Assume we have a class named Department then

Department d; is a reference variable of type class Department which can hold the object of class Department.

d = new Department(); this statement instantiates an object of Department and now the reference variable d holds the object of Department class, simply Department object gets created.

can also write as single line statement Department d = new Department

2) Java implements run time polymorphism by using dynamic method dispatch.

Dynamic method dispatch is a mechanism by which a call to a method overridden is resolved at run time.

When overridden method is called by reference, java determines which version of the method is called based on the type object it refer to.

This determination done at run time.

When reference variable of Parent class refers to the object of Child class, it is known as upcasting. Reverse is not possible i.e., Child class reference variable can't hold the object of Parent class

class Game {

public void type() {

System.out.println("Indoor & outdoor");

}

}

Class Cricket extends Game {

public void type() {

System.out.println("outdoor game");

}

public static void main(String[] args) {

Game gm = new Game();

Cricket ck = new Cricket();

gm.type();// calls Game version type()

ck.type();//calls Cricket version type()

gm=ck; //gm refers to Cricket object, reference variable of parent class holding the object of subclass

gm.type(); //calls Cricket's version of type

}

}

3)

D. 7

s1 gets instantiated at the statement s1="hello" --1

output at output = " The string reversed is: " --2

the loop executes for 5 times and every time a new string object gets created as strings are immutable in java. So +5 --7

//any query, post in the comment section

//give a thumbs up if you like it

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote