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
protectedmeans: same package or by inheritance. Since your classes are both in thedefault package(not recommended in real life),protectedenables access. By the way: if you tried to test java access control, you forgotdefault access(default access= no modifier =package private).privateaccess 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).