In: Computer Science
For Questions 1-3: consider the following code:
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()
{
Sysem.out.println(“A version of foo2() called);
return number;
}
public String foo3()
{
System.out.println(“A version of foo3() called”);
Return “Hi”;
}
}//end class A
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()”);
return (temp+” foo3”);
}
}//end class B
public class C extends B
{
public C()
{
super();
System.out.println();
}
public void foo1()
{
System.out.println(“C version of foo1() called”);
}
}//end class C
Assignment
B b1 = new B();
B b3 = new B();
int n = b3.foo2();
//b4 is a B object reference
System.out.println(b4.foo3());
public class N extends String, Integer
{
}
When you compile, you get the following message:
N.java:1: ‘{‘ expected
public class N extends String, Integer
^
1 error
Explain what the problem is and how to fix it.
A() called B() called |
Explanation:
It is given in the code that A is the superclass of B.
The constructor super() is invoked in constructor of B, hence A() is called and display on the screen and then B() is called. Therefore, constructor of B will print after the constructor of A.
A() called B() called A version of foo2() called B version of foo2() called |
Explanation:
It is given in the code that A is the superclass of B.
The constructor super() is invoked in constructor of B, hence A() is called and display on the screen and then B() is called. Therefore, constructor of B will print after the constructor of A.
The foo2() method is invoked in B class. In the method of foo2(), A (superclass) is invoked which results in last two lines of output.
A() called B() called A version of foo3() called B version of foo3() Hi foo3 |
Explanation:
It is given in the code that A is the superclass of B.
The constructor super() is invoked in constructor of B, hence A() is called and display on the screen and then B() is called. Therefore, constructor of B will print after the constructor of A.
Line 3 and line 4 is printed because foo3() method is called in class A and then foo3 method of class B is called.
Line 5 is printed because, A (superclass) is appended with string (“foo3”) in class B.
Fixing the problem:
Include 2 super class as member in a new class. After including them, extend that new class with class N.
You can also use the interfaces in order to overcome this problem, but first method is more optimized.