In JAVA please Use the following code fragments for the next 3 questions. Assume
ID: 3842725 • Letter: I
Question
In JAVA please
Use the following code fragments for the next 3 questions. Assume that:
Student, Employee, and Retired are all child classes of Person
All four classes have different implementations of a method called getMoney
Person p1 = new Person(...);
int m1 = p1.getMoney(); // statement1
Person p2 = new Student(...);
int m2 = p2.getMoney(); // statement2
Person p3;
if(m2 < 100000) {
p3 = new Employee(...);
} else {
p3 = new Retired(...);
}
int m3 = p3.getMoney(); // statement3
Question 1
The call to getMoney() in statement1 will invoke the method defined in which class?
Select one:
Person
Student
Employee
Retired
none of the above; this cannot be determined by examining the code
Question 2
The call to getMoney() in statement2 will invoke the method defined in which class?
Select one:
Person
Student
Employee
Retired
none of the above; this cannot be determined by examining the code
Question 3
The call to getMoney() in statement3 will invoke the method defined in which class?
Select one:
Person
Student
Employee
Retired
none of the above; this cannot be determined by examining the code
Explanation / Answer
This questions are of type of Method overriding which is part of dynamic Polymorphism in Java. in case of method overriding child class's method is being invoked.
Person p1 = new Person() // Person as a reference and Person as a object
Person p2 = new Student() // Person as a reference and Student as a object. p2.getMoney is method overriding and it will invoke student's getMoney method
Q -1
Answer : Person , Reason : here the object is instantiated using new Person() so , Person's getMoney is being called
Q-2
Answer: Student , Reason : here the object is instantiated using new Student() , so method overriding is being applied when call to getMoney () , so it will call the getMoney method of Student()
Q-3
None of the above, can not be determited by examining code, Reason : here we are not sure how p3 object is being intialized since if m<100000 then employee's getMoney will be called else Retired's getMoney is being called. So from code we are not sure which getMoney is being called it depends on m's value.
More info about oop in method overriding : https://stackoverflow.com/questions/20783266/what-is-the-difference-between-dynamic-and-static-polymorphism-in-java
Hope it is clear :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.