consider the following three classes: public class A { private int number; prote
ID: 3570678 • Letter: C
Question
consider the following three classes:
public class A
{
private int number;
protected String name;
public double price;
public A()
{
System.out.println( "A() called");
}
private void foo1()
{
System.out.println( "A version of foo1() called");
}
protected int foo2()
{
System.out.println( "A version of foo2() called");
return number;
}
public String foo3()
{
System.out.println( "A version of foo3() called");
return "Hi";
}
}
public class B extends A
{
private char service;
public B()
{
super();
System.out.println( "B() called" );
}
public void foo1()
{
System.out.println( "B version of foo1() called");
}
protected int foo2()
{
int n = super.foo2();
System.out.println( "B version of foo2() called");
return ( n + 5 );
}
public String foo3()
{
String temp = super.foo3();
System.out.println( "B version of foo3() called");
return ( temp + " foo3");
}
}
public class C extends B
{
public C()
{
super();
System.out.println( "C() called");
}
public void foo1()
{
System.out.println( "C version of foo1() called");
}
}
What is the output of the following code sequence:
B b4 = new B();
System.out.println( b4.foo3() );
A() called
B() called
A version of foo2() called
Hi
B version of foo2() called
A() called
B() called
A version of foo3() called
B version of foo3() called
Hi foo3
A() called
B() called
A version of foo3() called
B version of foo3() called
A() called
B() called
Hi foo3
A() called
B() called
A version of foo2() called
Hi
B version of foo2() called
A() called
B() called
A version of foo3() called
B version of foo3() called
Hi foo3
A() called
B() called
A version of foo3() called
B version of foo3() called
A() called
B() called
Hi foo3
Explanation / Answer
Given code is:
B b4 = new B();
System.out.println( b4.foo3() );
OUTPUT:
A() called
B() called
A version of foo3() called
B version of foo3() called
Hi foo3
Hence the correct option is b.
Explanation:
The statement B b4 = new B(); will create an object b4 of class B.
The super class of class B is class A.
So B's constructor invokes the constructor of class A is called. So the statement “A() called” is printed."
Then the statement "B() called” is printed."
The statement System.out.println( b4.foo3() ); will call the method foo3() with object b4.
super.foo3(); will output "A version of foo3() called". The value “Hi” is returned.
Then the statement System.out.println( "B version of foo3() called"); will output “ B version of foo3() called".
Then the statement return ( temp + " foo3"); will return “Hi foo3”
Then finally Hi foo3 is printed.
A() called
B() called
A version of foo3() called
B version of foo3() called
Hi foo3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.