Google+

83. Default access specifier






If we don't specify any access specifiers like Public, Private and Protected for the instance variables and methods of a class, we call it as default access specifier.

In case of default access specifier, all the methods and instance variables will be 'public' (i.e. accessible)  by default for all the classes inside the package, but where as they will be 'private'  (i.e. not accessible) by default  for the code that is outside the package.

In our previous post, we've specified all the instance variables and methods of the class as 'public'. In this case the code inside the package and outside the package is able to access the instance variables and methods which are specified as public. Click here to download this project and follow the below steps to find out how the default access specifier controls the access:

1. Import the downloaded project into Eclipse IDE and ensure that 'Ninth Project' with two packages under it (i..e. 'ninth_package' and 'outside_package' ) are displayed as shown below:



 2. Open the 'PublicMembers' class under the 'ninth_package' as shown below:



3. Remove the 'public' access specifier before the instance variable 'a' and sample( ) method as shown below and save:



This means, we have removed the 'public' access specifiers. So now we have the default access specifiers working on the members of the class.

4. Run the 'AccessPublicMembers' class as shown below: (i.e. we are executing a class that is under the same package of 'PublicMembers' class)


5. Click on 'Proceed' button if 'Errors in Workspace' dialog is displayed
6. After clicking 'Proceed' button, observe that output is displayed in the console as shown below:



At this point we've to understand that , if the instance variables and methods have no access specifiers specified, they are treated as default access specifiers, and these instance variables and methods can be accessed by all the classes inside the package.

7. Now Run the 'AccessOutside' class under the 'outside_package' as shown below:



8. Click on 'Proceed' button if  'Errors in workspace' dialog is displayed as shown below:

9. Observe than an error in the output is displayed in console as shown below (The error says that instance variable 'a' and sample( ) methods are not accessible)



Since we're trying to access the instance variables and methods which are specified as default access specifier. And we're trying to access these members of the class from a different package, we have got this error. It means instance variables and methods having default access will behave like private access specifier by default to all the code that is outside the package.

Download this project:

Click here to download the project (You can import the downloaded project into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

'Private' Access Specifier will be explained in the next post.



No comments: