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:
4. Run the 'AccessPublicMembers' class as shown below: (i.e. we are executing a class that is under the same package of 'PublicMembers' class)
6. After clicking 'Proceed' button, observe that output is displayed in the console as shown below:
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.