Using a package name to create objects in Java

I looked at another user's code and they encoded it using package names.

String filename = "";

java.io.PrintWriter writer;

writer = new java.io.PrintWriter(new java.io.FileWriter(filename));

Is syntax equivalent if it were not encoded with the package name? Is there any encoding with package names since Java allows this?

+5
source share
4 answers

You must use package names (or "fully qualified names" - this refers to the package name and class name together) if:

  • You need to use two identical names in the same source file.
  • You did not use importclasses that you use for any reason. (Usually crazy.)
  • import , , .
+8

, .

FQN , , .

import java.util.Date;

Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date(date);
+7

, , java.io :

import java.io.PrintWriter;
import java.io.FileWriter;

String filename = "";
PrintWriter writer;

writer = new PrintWriter(new FileWriter(filename));
+3

, , , , PrintWriter: java.io.PrintWriter java.io.

Not surprisingly, even in the "standard" classes there are quite a lot of duplicate names - for example, Date exists in java.util and java.sql, Queue exists in java.util and javax.jms - so you will come across this construct from time to time time.

+3
source

All Articles