In the below code the Consumer class can access the protected method of Parent class.How is it possible since there is no relation between Parent and Consumer class.Please explain
class Parent { public void method1(){ System.out.println("PUBLIC METHOD"); } private void method2(){ System.out.println("PRIVATE METHOD"); } protected void method3(){ System.out.println("PROTECTED METHOD"); } } public class Consumer { public static void main(String[] args){ Parent parentObj = new Parent(); parentObj.method1(); //parentObj.method2(); parentObj.method3(); } }
Thanks
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. The protected access modifier cannot be applied to class and interfaces.
2. The protected Keyword. While elements declared as private can be accessed only by the class in which they're declared, the protected keyword allows access from sub-classes and members of the same package.
Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control: At the top level— public , or package-private (no explicit modifier). At the member level— public , private , protected , or package-private (no explicit modifier).
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
protected
means: same package or by inheritance. Since your classes are both in the default package
(not recommended in real life), protected
enables access. By the way: if you tried to test java access control, you forgot default access
(default access
= no modifier = package private
).
private
access on the other hand means: access from nowhere except this particular class (and non-static inner classes, which are still member of the host-class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With