can anyone analyze this output? 1. abstract class Furniture { abstract void prnt
ID: 3741172 • Letter: C
Question
can anyone analyze this output?
1.
abstract class Furniture {
abstract void prnt();}
class Recliner extends Furniture {
void prnt() { System.out.println("I'm a recliner");}
}
class LaZBoy extends Recliner {
void prnt() { System.out.println("I'm a lazboy");}
}
public class furnitureTest2 {
public static void main(String[] args) {
Furniture [] A = { new Recliner(), new Recliner(), new LaZBoy()};
for (int i=0; i<3; ++i)
A[i].prnt();
}
}
output
I'm a recliner
I'm a recliner
I'm a lazboy
2.
class A { int x = 1; }
class B extends A { }
class C extends B { int x = 2;}
public class classTest {
public static void main(String[] args) {
A w = new A(); System.out.println(w.x);
B u = new B(); System.out.println(u.x);
C v = new C(); System.out.println(v.x);
A [] a = { new A(), new B(), new C()};
for (int i=0; i<3; ++i)
System.out.println(a[i].x);
}
}
output :
1
1
2
1
1
1
Explanation / Answer
1)
when Array Furniture is initialized in main method
Furniture [] A = { new Recliner(), new Recliner(), new LaZBoy()};
A[0] holds reference of Recliner()
A[1] holds reference of Recliner()
and A[2] holds reference of LaZBoy()
Hence, when
for (int i=0; i<3; ++i)
A[i].prnt();
in implemented,
prnt() method of Recliner() is called on i = 0 and 1,
and prnt() method of LaZBoy() on i = 2;
Output:
I'm a recliner
I'm a recliner
I'm a lazboy
2)
A w = new A();
// variable x of class A is fetched and printed out
System.out.println(w.x);
// output: 1
B u = new B();
// variable x of class B is fetched and printed out,
since class B extends class A, it takes value of x from A
System.out.println(u.x);
// output: 1
C v = new C();
// variable x of class C is fetched and printed out
System.out.println(v.x);
// output: 2
A [] a = { new A(), new B(), new C()};
A[0] holds reference of class A() => A a = new A();
A[1] holds reference of class B() => A a = new B();
and A[2] holds reference of class C() => A a = new C();
Since object is of class A reference to C, when for loop is implement, value of x is printed out for class A only
output:
1
1
1
Final output:
1
1
2
1
1
1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.