Suppose, you have two packages in a project and if you want to use a public specified class of package1 in a class under package2, then you have to import the class under package1 into the class under package2 as shown below:
Lets find out what happens when we don't import the class under package1 into the class under package2 by implementing this on Eclipse IDE:
1. Create a project say 'Project B1' as shown below:
6. Import 'ClassP1' of 'package1' into 'ClassP2' of 'package2' as shown below:
7. Now access the public member i.e. sample( ) method of 'ClassP1' by calling it as shown below:
9. Observe that the output is displayed in the console as shown below:
Click here to download this project containing 'ClassP1' and 'ClassP2' class files used in this post (You can download this project and import into Eclipse IDE on your machine)
In the previous example, we've only imported single class from a different package to access it. Now lets try to import more than one class under a package, by importing the package itself instead of importing two classes in separate statements. Instead of writing import statement for each and every class under 'package1' as shown in the below example syntax:
import package1.ClassP1; //This statement will only import the 'ClassP1' under 'package1'
import package1.ClassTwo; //This statement will only import the 'ClassTwo' under 'package2'
we've to import the package directly to import all the class files under 'package' at once using the below example syntax:
import package1.*; //This statement will import all the class files under the 'package1'
Lets implement importing complete package on Eclipse IDE:
1. In the above 'Project B1', add one more public specified class 'ClassTwo' under 'package1' as shown below and save:
3. Create an object for 'ClassTwo' of 'package1' and access the public specified instance variable 'a' of 'ClassTwo' in 'ClassP2' class as shown below:
5. Observe that the output is displayed in the console as shown below:
8. Observe that the same output is displayed in console as it was displayed in the above step 5 as shown below:
Download this project:
Click here to download the project containing 'ClassP1', 'ClassTwo' and 'ClassP2' class files used in this post (You can download this project and import into Eclipse IDE on your machine)
Please comment below to feedback or ask questions.
'Interfaces' concept will be explained in the next post.