0

if the following Java code were to appear in a control program that used the classes A,B and C what would be the outputs

class A implements Once { public void one () { System.out.println("A.1") ;} public void two () { one(); System.out.println("A.2") ;} public void sayItOnce () { System.out.println("I'll say it once") ;} } class B extends A implements Once, Twice { public void one (int x) { System.out.println("B.1" + x) ;} public void two () { System.out.println("B.2") ;} public void sayItTwice () { System.out.println("\"I'll say it Twice") ;} } class C extends A { public void one() { System.out.println("C.1") ;} } interface Once { void sayItOnce (); } interface Twice { void sayItTwice (); } class control1{ //(i) A a0 = new B (); a0.two(); //(ii) B b1 = new B() b1.one(4); b1.one(); //(iii) Once r1 = new B(); r1.sayItOnce(); //(iv) Twice b2 = new Twice(); b2.sayItTwice(); //(v) C c = new A(); c.two(); //(vi) A a2 = new B(); a2.sayItTwice(); //(vii) A a3 = new C(); a3.two(); }

1st Jan 2018, 5:08 PM
Martin Toomey
Martin Toomey - avatar
2 odpowiedzi
0
can someone explain this code and the output it would give? this is the exact code given in a previous exam question. I cant get it to compile to test the output
1st Jan 2018, 5:10 PM
Martin Toomey
Martin Toomey - avatar
0
Got the code to work. class A implements Once { public void one () { System.out.println("A.1") ;} public void two () { one(); System.out.println("A.2") ;} public void sayItOnce () { System.out.println("I'll say it once") ;} } class B extends A implements Once, Twice { public void one (int x) { System.out.println("B.1" + x) ;} public void two () { System.out.println("B.2") ;} public void sayItTwice () { System.out.println("\"I'll say it Twice") ;} } class C extends A { public void one() { System.out.println("C.1") ;} } interface Once { void sayItOnce (); } interface Twice { void sayItTwice (); } class Control{ public static void main (String args[]) { System.out.println("\n(i)"); A a0 = new B (); a0.two(); System.out.println("\n(ii)"); B b1 = new B(); b1.one(4); b1.one(); System.out.println("\n(iii)"); Once r1 = new B(); r1.sayItOnce(); System.out.println("\n \t(iv) ERROR"); //Twice b2 = new Twice(); //b2.sayItTwice(); System.out.println("error: Twice is abstract; cannot be instantiated"); System.out.println("\n \t(v) ERROR"); System.out.println(" C c = new A()"); System.out.println(" c.two()"); System.out.println(" incompatible types: A cannot be converted to C"); System.out.println("\n \t(vi) ERROR"); A a2 = new B(); //a2.sayItTwice(); System.out.println("Compiliation error"); System.out.println("there is no sayItTwice() method in Class A"); System.out.println("\n(vii)"); A a3 = new C(); a3.two(); } }
2nd Jan 2018, 1:16 PM
Martin Toomey
Martin Toomey - avatar