Wednesday, June 3, 2020

JAVA FAQs

1)What are the various access modifiers in Java ?

Ans) In Java, access modifiers are the keywords used before a class name ,method name constructor name,variable name and Interface name which defines the access scope of the respective entity. The types of access modifiers that are available in java:

a. Public : In java The public access modifier is specified using the keyword public. Public modifier can be used for Classes,Methods,Fields (Variables),Interfaces and constructors which are accessible from anywhere.

  • The public access modifier has the widest scope among all other access modifiers.
  • Classes, methods or data members which are declared as public are accessible from every where in the program. There is no restriction on the scope of a public data members.

b. Protected: In java the protected access modifier is specified using the keyword protected.The methods or data members declared as protected are accessible within same package or sub classes in different package.

Method,Field can be accessed from the same class to which they belong or from the sub-classes,and from the class of same package,but not from outside.

c. Default: In java no key required .When no access modifier is specified for a class , method or data member – It is said to be having the default access modifier by default. Method,Field,class can be accessed only from the same package and not from outside of it's native package.

d. Private:  In java the private access modifier is specified using the keyword private.The methods or data members declared as private are accessible only within the same class in which they are declared.The members declared as private will not be able to access in any other class of same package or other package .

  • In java top level Classes or interface can not be declared as private because private means “only visible within the enclosing class”.



                                    Default   Private    Protected   Public 
 Same Class Yes Yes Yes Yes
 Same Package
 Sub Class
 Yes No Yes Yes
 Same Package 
 Non Sub Class
 Yes No Yes Yes
 Different Package
 Sub Class
 No No Yes Yes
 Different Package
 Non Sub Class
 No No No Yes

No comments:

Post a Comment

Hello Buddy, if you have any doubts or need any clarification , feel free to comment. Thanks.