Java Programming - Declarations and Access Control - Discussion

5. 


package testpkg.p1;
public class ParentUtil 
{
    public int x = 420;
    protected int doStuff() { return x; }
}

package testpkg.p2;
import testpkg.p1.ParentUtil;
public class ChildUtil extends ParentUtil 
{
    public static void main(String [] args) 
    {
        new ChildUtil().callStuff();
    }
    void callStuff() 
    {
        System.out.print("this " + this.doStuff() ); /* Line 18 */
        ParentUtil p = new ParentUtil();
        System.out.print(" parent " + p.doStuff() ); /* Line 20 */
    }
}
which statement is true?

[A]. The code compiles and runs, with output this 420 parent 420.
[B]. If line 18 is removed, the code will compile and run.
[C]. If line 20 is removed, the code will compile and run.
[D]. An exception is thrown at runtime.

Answer: Option C

Explanation:

The ParentUtil instance p cannot be used to access the doStuff() method. Because doStuff() has protected access, and the ChildUtil class is not in the same package as the ParentUtil class, doStuff() can be accessed only by instances of the ChildUtil class (a subclass of ParentUtil).

Option A, B and D are incorrect because of the access rules described previously.


Meme said: (Sep 16, 2014)  
ChildUtil is a subclass of ParentUtil, therefore he can access the protected members!

Vaibhav said: (Jun 12, 2016)  
Why not The code compiles and runs, with output this 420 parent 420?

Manoj said: (Nov 24, 2017)  
When i run the program i got the output "this 420 parent 420" i.e. option A.

I have not removed the any line.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.