问题
What's the difference between a package and an import? Please give an example.
Why can't we just use import java.util.*;
?
Doesn't it give access to all the others automatically?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
回答1:
sentence "import java.util." imports only the classes under the util package. You can use "import java.util.regex." to import Matcher and Pattern classes . A package is a namespace for your classes, it's used to group related classes togheter and for access privilege reasons.
回答2:
Package is used to put all one Module related into one specified Folder for a better understanding ,whereas import is used to import the specific class that we need to run our application/class(Like we use Java.Util...etc).
回答3:
package name is user defined its what you give,
Ex: package test;
import package is used to get already predefined packages in java to be used in your current package
Ex: if you want to use "util" package in your test package,
package test;
java.util.Scanner;
Here util is java predefined package and Scanner is the class present in util package.
回答4:
Package is used to put all our related classes into one specified Folder for a better understanding ,whereas import is used to import(get) the needed or the dependent classes to run our application/class.
来源:https://stackoverflow.com/questions/23580284/whats-the-difference-between-a-package-and-an-import