Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java protected method accessibility

Tags:

java

oop

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

like image 394
JavaUser Avatar asked Jun 17 '10 04:06

JavaUser


People also ask

Is protected accessible to subclass?

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.

Who can access protected in Java?

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.

What are the possible access modifiers a protected method?

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).

Can protected members be accessed by objects Java?

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.


1 Answers

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).

like image 117
atamanroman Avatar answered Oct 02 '22 19:10

atamanroman