OCA Java SE 8 Mock Exam - OCA Mock Exam Question 5








Question

What is the output of the following code?

     public class Main{
          public static void main(String[] args) { 
            Shape rectangle = new Rectangle(5);  // A
            System.out.println(","+rectangle.hasEdges()); // B
          } 
     }
     
     class Shape { 
          public Shape() { 
            System.out.print("Shape"); 
          } 
          public Shape(int edge) { 
            System.out.print("ShapeEdge"); 
          } 
          private boolean hasEdges() { 
            return false; 
          } 
     } 
     class Rectangle extends Shape { 
       public Rectangle(int age) { 
         System.out.print("Rectangle"); 
       } 
       public boolean hasEdges() { // C
         return true; 
       } 
     }  
  1. ShapeRectangle,false
  2. ShapeRectangle,true
  3. RectangleShape,false
  4. RectangleShape,true
  5. ShapeAgeRectangle,false
  6. ShapeAgeRectangle,true
  7. The code will not compile because of line A.
  8. The code will not compile because of line B.
  9. The code will not compile because of line C.




Answer



H.

Note

In the following code, the Rectangle object is instantiated using the constructor that takes an int value.

Shape rectangle = new Rectangle(5);  // A

Since there is no explicit call to the parent constructor, the default no-argument super() is inserted as the first line of the constructor.

          public Shape() { 
            System.out.print("Shape"); 
          } 

The output is then Shape, followed by Rectangle in the child constructor.

The method hasEdges() looks like an overridden method, but it is actually a hidden method since it is declared private in the parent class.

Because the hidden method is referenced in the parent class, the parent version is used, so the code outputs false, and option A is the correct answer.

     public class Main{
          public static void main(String[] args) { 
            Shape rectangle = new Rectangle(5); 
            System.out.println(","+rectangle.hasEdges()); 
          } /*www.  j  a v  a 2  s  .  co  m*/
     }
     
     class Shape { 
          public Shape() { 
            System.out.print("Shape"); 
          } 
          public Shape(int edge) { 
            System.out.print("ShapeEdge"); 
          } 
          private boolean hasEdges() { 
            return false; 
          } 
     } 
     class Rectangle extends Shape { 
       public Rectangle(int age) { 
         System.out.print("Rectangle"); 
       } 
       public boolean hasEdges() { 
         return true; 
       } 
     } 

The code above generates the following result.