Given a java source file:
class x {
x () {}
private void one () {}
}
public class Y extends x {
Y () {}
private void two () {one();}
public static void main (string [] args) {
new Y().two ();
}
What changes will make this code compile?
A.
adding the public modifier to the declaration of class x
B.
adding the protected modifier to the x() constructor
C.
changing the private modifier on the declaration of the one() method to protected
D.
removing the Y () constructor
E.
removing the private modifier from the two () method
Explanation:
Using the private protected, instead of the private modifier, for the declaration of the one() method,
would enable the two() method to access the one() method.
Corrext answer is C and E. For new Y().two() to compile, method two() must not be private
Sorry, I now see method two() is called within class Y. The correct answer is C
Correct answer is C.
Private Access Modifier – private:
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Protected Access Modifier – protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members’ class.
★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Access Control and Inheritance:
The following rules for inherited methods are enforced:
Methods declared public in a superclass also must be public in all subclasses.
Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.