Java OCA OCP Practice Question 2317

Question

Given that classes Shape and Rectangle exist in separate packages and source code files, examine the code and select the correct options.

package mypkg; 
public class Shape { 
    protected String name = "Base"; 
} 
package pack2; 
import mypkg.*; 
class Rectangle extends Shape{ 
    Rectangle() { 
        Shape cls1 = new Shape();      //line 1 
        name = "Derived";                //line 2 
        System.out.println(cls1.name);   //line 3 
    } 
} 
  • a Rectangle can extend Shape but it can't access the name variable on line 2.
  • b Rectangle can't access the name variable on line 3.
  • c Rectangle can't access Shape on line 1.
  • d Rectangle won't compile.
  • e Line 3 will print Base.
  • f Line 3 will print Derived.


b, d

Note

A derived class can access a protected member of its base class, across packages, directly.

But if the base and derived classes are in separate packages, then you can't access protected members of the base class by using reference variables of class Base in a derived class.

So, Rectangle doesn't compile.

Options (e) and (f) are incorrect because Rectangle won't compile.




PreviousNext

Related