10

我们编程课上的老师在谈论“不合格的名字”,但我想知道它们到底是什么。

我怀疑诸如方法名称之类的东西是不合格的,但我不确定。

有谁能给我解释一下吗?我需要知道这一点,因为我需要解释 Java 以何种方式看起来是不合格的名称。

4

5 回答 5

19

限定名称是具有完整路径的名称,例如:

java.util.ArrayList list;

不合格的名称只有最后一部分:

import java.util.*;

ArrayList list;

该术语也可以适用于字段和方法。


那么,如果您可以导入类,为什么还需要使用限定名呢?

当您使用两个类时需要它,虽然它们来自不同的包,但它们共享相同的名称。一个经典的例子是来自 JDK 的可笑命名的类:

java.sql.Date

顺便延伸

java.util.Date

需要引用这两个类的实例是相当普遍的,因此您需要如下代码:

public void process(java.util.Date fromDate) {
    RowSet rows = <run query with fromDate as parameter>
    while (rows.nsxt()) {
        java.sql.Date date = rows.getDate(1);
        // code that needs date
    }
}

如果您使用两个同名类,则无法避免至少限定一个 - 您可以导入一个,但同时导入两个会产生歧义。

于 2015-01-15T15:18:18.847 回答
5

Java 中的限定名称包括类、接口、枚举或字段源自的特定包。

示例: java.util.ArrayList是一个完全限定的名称。

非限定名称只是没有包信息的类、接口、枚举或字段。

例子: ArrayList

于 2015-01-15T15:18:24.640 回答
2

例如 com.yourcompany.domain.Person 是完全限定的类名,Person 是类名或非限定类名。

于 2015-01-15T15:19:12.573 回答
1

限定名称: org.springframework.jdbc.core.JdbcTemplate
它有包名org.springframework.jdbc.core,然后是类名JdbcTemplate

Unqualified Name: JdbcTemplate 只有类名,没有包名。

例如:限定名称是您家的完整地址,非限定名称只是您的家庭名称。

于 2015-01-15T15:22:01.660 回答
0

Adding to the conversation a piece that has not been mentioned, yet (and that is not directly asked about but I believe is a helpful adendum to the conversation):

All names in Java require qualification; however, some are so integral to Java's operation that they are assumed - or, defaulted - to be "in the class" you are coding (or imported). Liskov (2000) gives a great example of this: java.lang - the class that contains such objects as String.

You often will see unqualified names in Java. This often has to do with the location of a class or method relative to the class in which you are attempting to access it (same package). Above, other posters have mentioned the concept of packages in Java.

Packages allow you to resolve - or, perhaps, better prevent - naming collisions. Each package in a program can duplicate the class names, etc. of another package. In this case, fully qualified names are used to access the correct class (as is seen in other answers). You can also import a package to avoid using its fully qualified name; however, should two imported classes contain a naming collision, you'll have a bit of problem.

于 2015-01-15T16:21:24.600 回答