Recently I was doing some coding using the java.nio.file package introduced in Java 7 and saw an example using Path like this:
Path path = Paths.get("C:\\Users");
Given that Path is an interface I was confused on how you could have a reference to it, however after some research I found out that a reference to an interface is allowed but it must point to a class that implements the interface. Looking on from this I looked at the Paths class and saw that it didn't implement Path. Looking at the source code the actual method Paths.get method is as follows:
public static Path get(String first, String... more) {
return FileSystems.getDefault().getPath(first, more);
}
the method first returns an object of type FileSystem (from an abstract class I think) using what I believe is called a static factory method, but FileSystem also doesn't implement the interface.
My question is does anyone know/able to explain where the Path interface is actually implemented as I cannot seem to find where this occurs.
If you look carefully you will notice that the method getPath
from FileSystem
object returns implementation of Path interface. By invoking FileSystems.getDefault()
you will retrieve implementation of FileSystem
interface which will depend on system. On Linux system you will get LinuxFileSystem
object witch extends UnixFileSystem
class.
You can look for example at UnixFileSystem
class from openjdk which is implementation of FileSystem
interface.
Here is the link with implementation of getPath
method from UnixFileSystem, which will return instance of UnixPath.
You must remember that FileSystems.getDefault
return implementation dependent on the operating system. Furthermore source code of those classes isn't available in oracle jdk.