[英]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. 我对Java还是很陌生,如果这是一个愚蠢的问题,很抱歉,为什么我们需要在接口中导入库,我有些困惑。
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? 您为什么需要在这里导入DataSource?
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. 因此,除非您导入
javax.sql.DataSource
,否则不会识别您在setDataSource
声明的参数的类型。
You don't need to import. 您不需要导入。 You can use fully qualified names like
javax.sql.DataSource
everywhere instead of just DataSource
. 您可以在各处使用完全限定的名称,例如
javax.sql.DataSource
,而不仅仅是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. 如果您使用的是类/接口/等,则可能仍需要使用
FQN
。 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);
}
这是为了指定您要在接口中使用哪种数据类型,来自哪个包,在一个项目中可能存在具有相同名称的不同类型的数据,因此需要显式指定该数据类型,进一步实施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.