0

So I have some fundamental gap in understanding.

I create Path object - Path p = Paths.get("/");

So Path is interface thereby it cannot be instantiated. But Paths.get() method has Path return type. I know it is common practice to use interface object reference. But how does it work under the hood? I thought it creates some anonymous class implementing Path interface. But the I tried to invoke .getClass() method on Path object and it returned: class sun.nio.fs.UnixPath.

Please explain briefly how does it work.

eugene p
  • 9
  • 3
  • nvm figured out – eugene p Apr 12 '21 at 11:13
  • Paths is not an interface (note Paths vs Path). You call a static .get() method that returns an object that implement the Path interface. – nos Apr 12 '21 at 11:15
  • You need to know about [Anonymous Classes][1]. By concept there is an actual class involved. [1]: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html – Rajnish Mishra Apr 12 '21 at 11:16
  • 1
    *"I thought it creates some anonymous class implementing Path interface"* — It doesn't have to be anonymous. – MC Emperor Apr 12 '21 at 11:17
  • @nos yep, should've go deeper. I see it invokes of() method eventually and it returns concrete class object - UnixPath in my case (Mac OS) – eugene p Apr 12 '21 at 11:46

0 Answers0