Google+

115. Packages






Packages are used to organize the classes which belong to the same category or which provide similar functionality. So Class file are categorized using Packages.

Example -

Lets say our Java Project is 'Facebook' and now lets create Packages to organize the classes under various packages. I will divide the Facebook Project into different sections using the Packages 'newsFeed', 'events', 'friends', 'groups', 'photos' , 'profile' etc. Now I will categorize the Classes which belong to newsFeed of Facebook project under 'newsFeed' package, Classes which belong to events under 'events' package and so on...

Lets implement this on Eclipse IDE:

1. Create a project called 'Facebook' as shown below:



2. Right on the 'Facebook' project and click on 'New' -> 'Package' option as shown below:


3. Ensure that a 'New Java Package' dialog is displayed as shown below:



4. Ensure that the name of the project 'Facebook' is displayed in the 'Source Folder' text box, enter name of the package say 'newsFeed' into the 'Name' text box and click on 'Finish' button as shown below:



5. Ensure that the newly created package is displayed on Eclipse IDE as shown below:



6. In the similar manner lets add more packages under the project 'facebook' as shown below:



7. Lets add the Java class files under packages by selecting the packages they belong to.
8. Right click on the package 'events' and select 'New' -> 'class' option as shown below:


9. Ensure that a 'New Java Class' dialog is displayed as shown below:


10. Ensure that the project name 'Facebook' and package name 'events' are displayed in the 'Source folder' & 'Package' text box, type class name 'Events' into the 'Name' field and  click on 'Finish' button as shown below:


11. Ensure that the newly added 'Events' class is added under 'events' package as shown below:


12. Ensure that 'package events;' code is displayed by default in the 'Events.java' class file as shown below:


13. Now lets add the functions of the events functionality like 'CreatingEvents', 'Viewing Upcoming Events' , 'EditingEvents' etc as methods to the 'Events' class as shown below and save:



14. Ensure that the names of the created methods are displayed under the 'Events' class in package explorer as shown below:


15. In the similar manner we can create other class files by categorizing them the packages they fall into as shown below:




Download this project:

Click here to download the 'Facebook' project used in this post (You can download and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

'Package and Access Protection' topic will be explained in the next post.



No comments: