Question 4-2 Fix the following program to produce the output. You SHOULD NOT CHA
ID: 3876633 • Letter: Q
Question
Question 4-2 Fix the following program to produce the output. You SHOULD NOT CHANGE/ADD any statement in the MAIN method. AND explain why this program is not working at this moment, and how you fixed the errors in DETAIL at the bottom of the program. class A4 public String x ) (return "Ax"; class B4 extends A4 int i = 2; public string y () freturn "Bay";) public string z ) treturn "B.z." public class PolymorphismWhy4( public static void main(String[] args) [ A4 obj = new B4(); System.out.println (obj.i); Sys (obj-X( ) ) ; (obj.y.)) // output System.out.println (ob J.Z.( ) ) ; Ax / Explain why and how in detail hereExplanation / Answer
Correct Code
Why and How
The example you are referring to is called Upcasting in java. A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. In main function, subclass object has been initialized with the help of superclass reference variable.This just creates an object of type subclass (B4) but assigns it to the type superclass(A4). All the subclasses' data is created etc, but the variable cannot access the subclasses data/functions. In other words, you cannot call any methods or access data specific to the subclass, you can only access the superclasses stuff. This is why the program was not working. since methods x(), y() are the member of the subclass, not the superclass
However, we can still access the methods using explicit typecasting e.g.
((B4)obj).y(); and ((B4)obj).z();
since we are not allowed to change the main function, we have to declare all data members and methods in super class only.If the methods are present in SuperClass but overridden by SubClass, it will always be the overridden method that will be executed. But this is not true in case of data members. Data member from superclass will get executed. Hence, when we execute the corrected code, value that will be printed for 'x' is totally dependent on superclass initialization and methods (x,y) will be overridden by the methods of the subclass and thus producing the desired result.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.