Java OCA OCP Practice Question 1574

Question

This question may be considered too advanced for this exam. Given:

class MyBaseClass{
    public MyBaseClass (int i){  }
}

abstract class MyClass extends MyBaseClass{
    public MyClass (int i){ super (i);  }
    public abstract void m1 ();
}

public class MyTest{
    public static void main (String [] args){
        MyClass ms = new MyClass (){
            public void m1 ()  { System.out.println ("In MyClass .m1 ()");  }
        };/*from ww  w. j  a  va2s .c om*/
        ms.m1 ();
     }
 }

What will be the output when the above code is compiled and run?

Select 1 option

  • A. It will not compile.
  • B. It will throw an exception at run time.
  • C. It will print In MyClass .m1 ()
  • D. It will compile and run without any exception but will not print anything.


Correct Option is  : A

Note

When you define and instantiate an anonymous inner class for an abstract class, the anonymous class is actually a subclass of the abstract class.

Since the anonymous class does not define any constructor, the compiler will add the default no-args constructor to the anonymous class.

It will try to call the no-args constructor of its super class MyClass.

But MyClass doesn't have any no-args constructor.

Therefore, it will not compile.

The anonymous inner class should have been created like this:.

MyClass ms = new MyClass ( someInteger ){  ...  };



PreviousNext

Related