Java OCA OCP Practice Question 1207

Question

How many lines of the following program contain compilation errors?

package mypkg; //from   w  ww  .ja  v  a2 s .c o  m
public class Main { 
        private int v = 4; 
        public void Main() { 
           super(); 
        } 

        public Main(int v) { 
           this.v = this.v; 
        } 
        public static void main(String[] endless) { 
           System.out.print(new mypkg.Main(2).v); 
        } 
} 
  • A. None
  • B. One
  • C. Two
  • D. Three


B.

Note

The code does not compile, so Option A is incorrect.

The class contains two constructors and one method.

The first method, Main(), looks a lot like a no-argument constructor,

but since it has a return value of void, it is a method, not a constructor.

Since only constructors can call super(), the code does not compile due to this line.

The only constructor in this class, which takes an int value as input, performs a pointless assignment, assigning a variable to itself.

While this assignment has no effect, it does not prevent the code from compiling.

Finally, the main() method compiles without issue since we just inserted the full package name into the class constructor call.

This is how a class that does not use an import statement could call the constructor.

Since the method is in the same class, and therefore the same package, it is redundant to include the package name but not disallowed.

Because only one line causes the class to fail to compile, Option B is correct.




PreviousNext

Related