You are currently viewing Java OOP – Java Packages

Java OOP – Java Packages

A package is a group of classes, interfaces and other packages. We can organize our classes and interfaces using packages. In java there are two types of packages.

  1. Built-in packages
  2. User defined packages

Built – In Packages

In java we can see packages that defined already. They are known as Built-in packages. Let’s see an example.

pc1

This package is used when we need user input.

java – top level package

util – sub package

Scanner – class that presents in the util package

User Defined Packages

That packages we create are called user defined packages. Let’s see an example.

pc2

Example.java file is created inside the package “abc”.

Let’s see how to use this package in another program.

pc3

To use the class “Example” inside the class “Test”, I have imported the package “abc”. In the above program i have imported the package as “abc.Example”. This only imports the “Example” class. Imagine that there are many classes inside the package “abc”. Then you can import the package like given below to use all of those classes inside the package.

pc4

You can create a class inside a package while importing another package also. The order should be like given below.

pc5

You can use fully qualified name to avoid the import statement. Lets see an example to understand this.

pc6

Here I have used the full qualified name such as package_name.class_name to create the object of it.

Sometimes class name conflict may occur. Assume that you created two classes with the same name in two different packages and you need to import all from those packages. Then that will throw a compile error. Therefore in that sort of situations you should use full qualified name method.

I hope you guys understood about the Java packages. This is important to learn the next article. It is on the topic “Java Access Modifiers”.

Thank you.

Sharing is caring!

Chathura Buddhika

Working as a Frontend Software Engineer at leading company in Sri Lanka, and has hands on experience in web application development and mobile application development.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments