Zafir Stojanovski
Zafir Stojanovski

Reputation: 481

Creating a path object when Path is an interface?

I don't understand how a Path object can be created if the Path class is an interface itself.

Path path = Paths.get("...");

I'm having a real struggle, and I'm also a beginner, so please help out!

Upvotes: 1

Views: 836

Answers (3)

mm759
mm759

Reputation: 1424

An interface defines a type in Java. If you get an object that has type Path you and the compiler will know the methods that may be called. You will additionally know what you may expect the methods to do. Paths.get returns an instance of a class that implements the interface Path.

You don't know the implementing class and you should not have to know it so that your code does not rely on implementation details. Interfaces provide the possibility to implement "loose coupling". You can use an interface and write code that calls it's methods even if there is still no implementation (useful especially for a top-down-approach). Interfaces enable you to have multiple implementations of an interface which specifies the common behaviour that all implementations have to implement. ArrayList and LinkedList are examples of multiple classes implementing the interface List. This is called polymorphism. Many standards include interfaces to specify a behavior. This allows multiple implementations of the stabdard to exist.

Upvotes: 1

Adel Khial
Adel Khial

Reputation: 424

assylias said that it returns a PathImpl which is a Path. If you're confused about the meaning of "is a", read about inheritance in java.

Upvotes: 0

assylias
assylias

Reputation: 328618

Imagine that the underlying code is something like this:

interface Path {}
class PathImpl implements Path {
  String path;
  PathImpl(String path) { this.path = path; }
}
class Paths {
  static Path get(String path) { return new PathImpl(path); }
}

So If you call Paths.get("abc") with my example, you will receive a new PathImpl("abc") which implements the Path interface.

Upvotes: 2

Related Questions