Using paths and paths in Java

The interaction between Path and Paths seems simple enough. You get a Path object using the Paths get() method. Then you can use the Path methods:

 Path p = Paths.get("C:\\directory\\filename.txt"); p.getFilename(); p.getRoot(); p.getParent(); etc... 

What scares me is that the Java documentation describes Path as an interface. Typically, an interface is just a collection of method signatures that you must implement in any class that claims to use it with the implements keyword.

However, in the case of Path, there is no keyword "implements", and you do not implement methods. They are already predetermined.

I obviously got the wrong end of the stick. Can someone explain what I misunderstood?

+4
source share
4 answers

This is the OOP replacement principle http://en.wikipedia.org/wiki/Liskov_substitution_principle

 If S is a T, then references to T can be changed to references to S 

In our case, this means that Paths can return an instance of any class that implements Path. If I print the actual class name

 System.out.println(p.getClass()); 

I will get

 class sun.nio.fs.WindowsPath 

As you can see, this is a concrete implementation of the path to Windows. Naturally, on Linux we would get something else. Using a static factory method that returns an interface allows this method to modify the actual implementation of this interface.

+5
source

Path is an interface. Select an object somewhere in your code and press F4 to get a type hierarchy. This will show you the actual implementations. You will see the following:

 Path - AbstractPath - WindowPath - ZipPath 

Paths is a specific implementation that provides a service for returning Path to Paths.get(filename) . The Paths class will instantiate one of the specific implementations that you can see in the type hierarchy. It is best to return the most general type that Path here. Thus, your own implementation is independent of the underlying Path implementation; it can be WindowPath or ZipPath .

+1
source
 Paths.get("C:\\directory\\filename.txt"); 

Returns the resulting Path object implemented (based on the OS). The path is obtained by calling the getPath() method FileSystem .

+1
source

Path is the interface, and Paths.get() is the factory method for creating specific implementations.

The exact exact class returned will depend on your operating system and file system type.

0
source

Source: https://habr.com/ru/post/1479690/


All Articles