What changes will make this code compile?

Given a java source file:
<code>
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 ();
}
</code>
What changes will make this code compile?

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.



Leave a Reply 4

Your email address will not be published. Required fields are marked *


Marin R

Marin R

Corrext answer is C and E. For new Y().two() to compile, method two() must not be private

Marin R

Marin R

Sorry, I now see method two() is called within class Y. The correct answer is C

Kalil Peixoto

Kalil Peixoto

Correct answer is C.

noir

noir

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.