Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - Pointing out the correct statements (Q.No. 5)
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?
The code compiles and runs, with output this 420 parent 420.
If line 18 is removed, the code will compile and run.
If line 20 is removed, the code will compile and run.
An exception is thrown at runtime.
Answer: Option
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.

Discussion:
6 comments Page 1 of 1.

Kalyani said:   4 years ago
Can anyone explain the exact answer?

Anil said:   6 years ago
The code will compile and run.
(1)

Vasavisreenivas said:   8 years ago
Actually, the option is A because I got the result as same as option A.
(1)

Manoj said:   8 years ago
When i run the program i got the output "this 420 parent 420" i.e. option A.

I have not removed the any line.
(1)

Vaibhav said:   9 years ago
Why not The code compiles and runs, with output this 420 parent 420?
(1)

Meme said:   1 decade ago
ChildUtil is a subclass of ParentUtil, therefore he can access the protected members!
(1)

Post your comments here:

Your comments will be displayed after verification.