Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Path and Paths in Java

Tags:

java

path

The interaction between Path and Paths seems simple enough. You get a Path object using Paths' get() method. You can then use Path's methods:

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

What's confusing me is the fact that the Java documentation describes Path as being an interface. Normally speaking, an interface is just a collection of method signatures which you need to implement in any class which declares that it uses it via the implements keyword.

However, in the case of Path, there's no 'implements' keyword used and you don't implement the methods. They're already predefined.

I've obviously got the wrong end of the stick somewhere. Can someone please explain what I've misunderstood?

like image 962
Ambiorix Avatar asked Mar 24 '23 01:03

Ambiorix


2 Answers

It is OOP substituion 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 it means that Paths can return an instance of any class which implements Path. If I print the actual class name

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

I'll get

class sun.nio.fs.WindowsPath

As you can see this is Windows specific Path implementation. Naturally on Linux we would get something different. Using static factory method returning an interface allows this method to change the actual implementation of this interface.

like image 144
Evgeniy Dorofeev Avatar answered Mar 26 '23 16:03

Evgeniy Dorofeev


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

Returns the resulting Path implemented Object(Based on OS).The Path is obtained by invoking the getPath() method of the default FileSystem.

like image 38
Suresh Atta Avatar answered Mar 26 '23 15:03

Suresh Atta