为什么java接口返回自身?
我正在读取当前代码
public class Find {
public static class Finder extends SimpleFileVisitor<Path>{
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern){
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
void find(Path file){
Path name = file.getFileName();
System.out.println("Name " + name);
if (name != null && matcher.matches(name)){
numMatches++;
System.out.println(file);
}
}
void done(){
System.out.println("Matched: " + numMatches);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
find(file);
return CONTINUE;
}
查看文件.getFileName(),它由一个接口表示
public interface Path
extends Comparable<Path>, Iterable<Path>, Watchable
但返回值如您在行中所见
System.out.println("Name " + name);
它必须是字符串,因为它是可打印的。
但是看看界面
/**
* Returns the name of the file or directory denoted by this path as a
* {@code Path} object. The file name is the <em>farthest</em> element from
* the root in the directory hierarchy.
*
* @return a path representing the name of the file or directory, or
* {@code null} if this path has zero elements
*/
Path getFileName();
它返回一个Path对象,为什么要这样做?
String
的操作数一起使用时,+
是String
串联运算符。您需要研究toString()
方法。
Java字符串教程介绍
+运算符广泛用于打印语句。例如:
String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod");
它打印
Dot saw I was Tod
这样的串联可以是任何对象。对于每个不是String的对象,其toString()方法被调用以将其转换为字符串。
基本上,所有引用类型都继承Object
类,从而继承toString()
方法。连接String
和不同类型的引用时,会调用该类型的toString()
方法,并连接生成的String
。
此语句为false:
它必须是字符串,因为它是可打印的。
当使用变量代替String
时,Java编译器将隐式调用对象的toString()
方法(所有对象都有)。对于Path
,它将输出路径的字符串表示。仅仅因为某个东西打印出文本并不意味着它是一个实际的String
实例。
Path getFileName()返回Path Object,所以每当我们打印对象时,它的toString()方法都会被调用,它是从Object类继承的。
因此Path的toString()方法被调用,它以字符串形式返回路径对象
所以如果有这样的方法的话,可以做一些类似path.getFileName().getName();
的事情来获取名称。