Java OCA OCP Practice Question 1497

Question

Consider the contents of following two files:

//File MyClass .java 
package a; //ww  w .  ja v  a2s  .c o  m
public class MyClass { 
   MyClass (){  } 
   public void  print (){ System.out.println ("MyClass");  } 
} 

//File MyClass2 .java 
package b; 
import a.*; 
public class MyClass2 extends MyClass { 
   MyClass2 (){  } 
   public void  print (){ System.out.println ("MyClass2");  } 
   public static void main (String [] args){ 
      new MyClass2 (); 
    } 
} 

What will be printed when you try to compile and run class MyClass2?

Select 1 option

  • A. It will print MyClass.
  • B. It will print MyClass2.
  • C. It will not compile.
  • D. It will compile but will not run.
  • E. None of the above.


Correct Option is  : C

Note

Note that there is no modifier for MyClass's constructor.

So it has default access.

Only classes in package a can use it.

Also note that class MyClass2 is in a different package and is extending from MyClass.

In MyClass2's constructor the compiler will automatically add super() as the first line.

But since MyClass() is not accessible in MyClass2, this code will not compile.




PreviousNext

Related