Q.Which statement from s1 to s6 (see below) cause compilation error? Assume the
ID: 3679838 • Letter: Q
Question
Q.Which statement from s1 to s6 (see below) cause compilation error? Assume the statement that causes compilation is deleted, what is the output when the program is executed?
class X{
void f1() { System.out.println("XXX"); }
}
class Y extends X{
void f1() { System.out.println("YYY"); }
}
class Z extends X{
void f1() { System.out.println("ZZZ"); }
}
class Test{
static void g(X a) { a.f1(); }
public static void main(String args[]){
Y y = new Y();
g(y);
Object obj = new Y(); obj.f1();
X x = new Z(); x.f1();
// s1 // s2 // s3 // s4 // s5 // s6
}
Explanation / Answer
class X{
void f1() { System.out.println("XXX"); } }
class Y extends X{
void f1() { System.out.println("YYY"); }
}
class Z extends X{
void f1() { System.out.println("ZZZ"); }
}
class Test{
static void g(X a) { a.f1(); }
public static void main(String args[]){
Y y = new Y();
g(y);
Object obj = new Y(); obj.f1();
X x = new Z(); x.f1();
// s1 // s2 // s3 // s4 // s5 // s6
}
} // extra bracket missing in code
The code is no completed , there is need of an Extra bracket at the end for the program to compile.
Now the line obj.f1(); was cause compilation error as Object is not a class here and we are making a object obj from that, which is not possible.
After this line is removed from the code .
The output will be
YYY
ZZZ
because when Y y = new Y(); is executed object of class Y is formed because of which YYY is printed and when X x = new Z(); is executed object x of class z is formed so control goes in class Z when f1 is called. hence the output.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.