Java import class methods

Using Package Members

The types that comprise a package are known as the package members.

To use a public package member from outside its package, you must do one of the following:

  • Refer to the member by its fully qualified name
  • Import the package member
  • Import the member’s entire package

Each is appropriate for different situations, as explained in the sections that follow.

Referring to a Package Member by Its Qualified Name

So far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts . You can use a package member’s simple name if the code you are writing is in the same package as that member or if that member has been imported.

However, if you are trying to use a member from a different package and that package has not been imported, you must use the member’s fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example.

You could use this qualified name to create an instance of graphics.Rectangle :

graphics.Rectangle myRect = new graphics.Rectangle();

Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the member or its package and then use its simple name.

Importing a Package Member

To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here’s how you would import the Rectangle class from the graphics package created in the previous section.

Now you can refer to the Rectangle class by its simple name.

Rectangle myRectangle = new Rectangle();

This approach works well if you use just a few members from the graphics package. But if you use many types from a package, you should import the entire package.

Importing an Entire Package

To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character.

Now you can refer to any class or interface in the graphics package by its simple name.

Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle();

The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A .

// does not work import graphics.A*;

Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package.

Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square , you could import Rectangle and its nested classes by using the following two statements.

import graphics.Rectangle; import graphics.Rectangle.*;

Be aware that the second import statement will not import Rectangle .

Читайте также:  What is my java version centos

Another less common form of import , the static import statement, will be discussed at the end of this section.

For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file).

Apparent Hierarchies of Packages

At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt . However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.

Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color , java.awt.font , or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt , you must import both packages with all their files:

import java.awt.*; import java.awt.color.*;

Name Ambiguities

If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name. For example, the graphics package defined a class named Rectangle . The java.awt package also contains a Rectangle class. If both graphics and java.awt have been imported, the following is ambiguous.

In such a situation, you have to use the member’s fully qualified name to indicate exactly which Rectangle class you want. For example,

The Static Import Statement

There are situations where you need frequent access to static final fields (constants) and static methods from one or two classes. Prefixing the name of these classes over and over can result in cluttered code. The static import statement gives you a way to import the constants and static methods that you want to use so that you do not need to prefix the name of their class.

The java.lang.Math class defines the PI constant and many static methods, including methods for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many more. For example,

public static final double PI = 3.141592653589793; public static double cos(double a)

Ordinarily, to use these objects from another class, you prefix the class name, as follows.

double r = Math.cos(Math.PI * theta);

You can use the static import statement to import the static members of java.lang.Math so that you don’t need to prefix the class name, Math . The static members of Math can be imported either individually:

import static java.lang.Math.PI;
import static java.lang.Math.*;

Once they have been imported, the static members can be used without qualification. For example, the previous code snippet would become:

Obviously, you can write your own classes that contain constants and static methods that you use frequently, and then use the static import statement. For example,

import static mypackage.MyConstants.*;

Note: Use static import very sparingly. Overusing static import can result in code that is difficult to read and maintain, because readers of the code won’t know which class defines a particular static object. Used properly, static import makes code more readable by removing class name repetition.

Читайте также:  Html header scrolling table

Источник

How to Import Classes in Java

“The concept of “class” must be known to almost any person who has gone to high school at least once in their life. In programming languages, a class is used to store elements with similar properties. It is used as a “blueprint” that can construct objects. A class is a combination of objects, variables, and functions. There is a certain way to define and import classes in different programming languages. Within this guide, we are elaborating on the syntax of importing the user-defined custom classes and the built-in class in a java program.”

Syntax

To import any sort of class or static package in the specific Java program file, you have to memorize the below-shown syntax of the Java code. This syntax starts with the Java keyword “import,” which is being used to import any package or a Java class. After the keyword “import”, you need to specify the name of a package followed by the name of a class to be imported from your Java language, i.e., Java.util is a package, and the “Scanner” is a class within it.

Example 01

While using this first illustration, we will be discussing a way to import built-in classes. Thus, we are working in the Eclipse IDE Java tool, where we have created a file “test.java”. In this Java file, we are going to get some input from the user and display it on the Eclipse console after importing the respective input class. Therefore, we have imported the “Scanner” class from the “java.util” package of Java programming.

The very same syntax has been used in this example that has been explained in the above paragraph. The “Scanner” class is a built-in Java class used to perform some input and output operations. After the class import, we have defined a custom user-defined class “test” that contains a main() driver method in it. The main() driver method starts with the initialization of a Scanner class object “t,” taking the “system.in” package in its output to specify that it is going to perform the input operations.

A string variable “V” got defined, and the “System.out.println” statement was tried out to ask a question from the user: “What is your name?” on the Eclipse IDE console. At the 8th line, we have been calling the nextline() function by making use of the Scanner class object “t” of Java to get the input from a user and save it to the string variable “V”. The last “System.out.println” function statement will print the “V” variable value at the same console. The program’s main() method of class “test” is completed here. To run this program, use the “Run” icon from the Eclipse IDE taskbar.

The output screen displays the question: “What is your name?” as shown. The user inputs their name and hits the “Enter” button, i.e., “John”. The string value of variable “V” got displayed.

Example 02

Let’s take a look at another Java example to use the built-in class. In this program, we are going to import the whole Java package along with its classes and interfaces using the “*” character instead of the class name, i.e., “java.util.*”. The “test” class has been started with the main() function that has been creating an object “s” for the built-in class “Stack”. This class is used here to create a stack of data.

Читайте также:  Python group by string

Using these object “s”, we are inserting and deleting the integer elements from the stack, i.e., “push” to insert and “pop” to delete. The “pop” function only pops the last inserted item from the stack. In the end, the remaining stack elements would be displayed via the println() function statement. Let’s run this program now.

On execution, the output shows only the 4 elements left in the stack.

Example 03

This example is going to elaborate on the method of importing the custom or user-defined class in Java programming. For this, you must have two Java files created in the Eclipse IDE. These file names are going to be our class names. The first file, “info.java,” contains an implementation of the user-defined class “info” after the import of the built-in “Scanner” class from the “java.util” package. The class “info” is initializing an object “s” of the Scanner class to make use of input operations in this program via the “System.in” package.

After this, two variables are defined, i.e., the string type “Name” variable and the integer type “Salary” variable. The getter and setter functions are used here. The getN() function asks for an input name from the user using the “NextLine” function and saves it to the variable “Name”. Then, it will return this value to the main() function. The sent() function is used here to set the value of the mutable “Name”. In a very similar way, the getSal() is the getter function to get the value for the integer variable “age” from the user using the nextInt() function. After that, this value would be returned to the main() function of the other file. The setSal() function sets the value for the “Salary” variable.

Now, the other file, “test.java,” contains the import statement to import the “info” class from the “info.java” file. It starts with the “test” class holding a main() function. The object “t” for the “info” class was created and utilized to call the getN(), and getSal() functions here to display the respective input values.

This is how you can import the user-defined custom classes in Java. The user inputted the name and salary, and it got exhibited as well.

Conclusion

This article explains the use of classes in Java programming, followed by an explanation of the syntax used to import the classes. For this, we have explained the way of importing built-in classes of Java in the first two examples, i.e., by importing and using the Scanner and Stack classes. After this, we have explained a way to import a custom class in a Java program, i.e., defining a class in one Java file and importing it to another Java file.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.

Источник

Оцените статью