Why is it needed to import libraries in an interface

I’m pretty new to Java, and sorry if this is a stupid question, and I’m a little confused why we need to import libraries in an interface.

I understand why you would need to import a library in classes, or main methods, as you are actually using the libraries. However, correct me if I’m wrong, in an interface, you’re just declaring the methods with parameters without actually ‘doing’ anything with it. You only actually use it when you implement the interface in a separate class?

For example:

import javax.sql.DataSource;

public interface ExampleInterface {

    public void setDataSource(DataSource ds);

}

Why would you need to import DataSource here?

You don’t need to import. You can use fully qualified names like javax.sql.DataSource everywhere instead of just DataSource.

But you need to do one or the other to specify the exact class/interface you’re referring to. The compiler doesn’t accept non-unique simple names for anything.

You might still need to use FQN if you’re using classes/interfaces/etc. with the same name, since we can’t import both due to naming conflict:

import javax.sql.DataSource;

public interface ExampleInterface {

    public void setDataSource(DataSource ds);
    public void setActivationDataSource(javax.activation.DataSource ds);
}

In an interface, you’re just declaring the methods with parameters without actually ‘doing’ anything with it

Yes, but you still declare them. So if you want them to be recognizable, you need to import the corresponding libraries. In your example you define a method :

public void setDataSource(DataSource ds); 

in your interface. So unless you import javax.sql.DataSource, the type of the parameter you declare in setDataSource will not be recognized.

It is to specify that what data type you are going to use in the interface, from which package, in one project there maybe different kind of data with the same name, so it needs to be explicitly specified, which type of DataSource is needed for further implementation.