Java OCA OCP Practice Question 1565

Question

What is the output of the following application?

package mypkg;/*from   ww w.  j  av a  2  s  .com*/
 
interface Printable { String print(); }
public class Main {
   public static void main(String[] matrix) {
      abstract class Shape {}
      class Rectangle extends Shape implements Printable {
         public String name = "r1";
         public String print() {return "r2";}
      }
      Rectangle prime = new Rectangle () {
         public String print() {return name;}  // y1
      };
      System.out.print(prime.print()+" "+name);
   }
}
  • A. r1 r1
  • B. r1 r2
  • C. The code does not compile because of line y1.
  • D. None of the above


D.

Note

The code does not compile, so Options A and B are incorrect.

The declarations of the local inner classes Shape and Rectangle compile without issue.

The anonymous inner class that extends Rectangle compiles without issue, since the public variable name is inherited, making Option C incorrect.

The only compilation problem in this class is the last line of the main() method.

The variable name is defined inside the local inner class and not accessible outside class declaration without a reference to the local inner class.

Due to scope, this last line of the main() method does not compile, making Option D the correct answer.

Note that the first part of the print() statement in the main() method, if the code compiled, would print r1.




PreviousNext

Related