The uncompleted programs to run in Java and in C are given b
The uncompleted programs to run in Java and in C++ are given below. Note that you need to create a driver class with the main method to run the Java program. Also, you need to write the main function to run the C++ program.
a). predict the output of the Java program.
b). run the Java program and compare your prediction to the actual output of the program.
c). Complete the C++ program such that it prints the same output as the Java program does. You need to use the given classes to generate the desired output.
The Java Program is:
class A {
public void p() {
System.out.println(“A.p”); }
public void q() {
System.out.println(“A.q”); }
public void r() {
p(); q(); }
}
class B extends A {
public void p() {
System.out.println(“B.p”); }
}
class C extends B {
public void q() {
System.out.println(“C.q”); }
public void r() { p(); q(); }
} …
A a;
C c = new C();
a = c;
a.r();
a = new B();
a.r();
a = new C();
a.r();
The C++ Program is:
class A {
public: virtual void p() {
cout << “A.p” << endl; }
void q() {
cout << “A.q” << endl; }
virtual void r() { p(); q(); }
};
class B : public A {
public: void p() {
cout << “B.p” << endl; }
};
class C : public B {
public: void q() {
cout << “C.q” << endl; }
void r() {
p(); q(); }
};
Solution
class A {
public void p() {
System.out.println(\"A.p\");
}
public void q() {
System.out.println(\"A.q\");
}
public void r() {
p();
q();
}
}
class B extends A {
public void p() {
System.out.println(\"B.p\");
}
}
class C extends B {
public void q() {
System.out.println(\"C.q\");
}
public void r() {
p();
q();
}
}
class Driver{
public static void main(String args[]){
A a; // instianite A class
C c = new C(); // Create C object
a = c; // assign c object to a
a.r(); // on calling r() the output would be B.p, C.q
a = new B(); // assign B object to a
a.r(); // on calling r() the output would be B.p,A.q
a = new C(); // assign C object to a
a.r(); // the output would be B.p, C.q
}
}
/* sample output
B.p
C.q
B.p
A.q
B.p
C.q
*/
#include <iostream>
using namespace std;
class A {
public: virtual void p() {
cout << \"A.p\" << endl; }
void q() {
cout << \"A.q\" << endl; }
virtual void r() { p(); q(); }
};
class B : public A {
public: void p() {
cout << \"B.p\" << endl; }
};
class C : public B {
public: void q() {
cout << \"C.q\" << endl; }
void r() {
p(); q(); }
};
int main(){
A a;
C c;
B b;
c.r(); // call r function of c object
b.r(); // call r function of b object
c.r(); // call r funciton of c object
}
/*
smaple output
*/


