[英]How can I use an interface as type in java?
I have created an interface named Leen
and created a class X that implements this interface, but when i go to main class to create a variable named x
like this 我创建了一个名为
Leen
的接口,并创建了一个实现该接口的类X,但是当我进入主类来创建一个名为x
的变量时,就像这样
Leen x;
x.printname();
The compiler gives me error: 编译器给我错误:
Connect.java:10: error: variable x might not have been initialized
You can't use an interface without implementation. 没有实现,就不能使用接口。 Implementation can be a concrete class or abstract class which implements your interface.
实现可以是实现您的接口的具体类或抽象类。 Based on your code, clearly there is no implementation for you interface.
根据您的代码,显然没有接口实现。 I'm also not sure where did you use the variable
p
. 我也不确定您在哪里使用变量
p
。 Kindly provide your whole class so that we can help you. 请提供您的整个课程,以便我们为您提供帮助。
Suppose if u want to access in the variable with out instantiating it u can make the variable static in the class. 假设如果您想在不实例化的情况下访问变量,则可以使该变量在类中为静态。 say
App
is ur class name and xyz is ur interface. 说
App
是您的类名,而xyz是您的界面。
class App implements xyz{
public static int x;
public static void printme(){
//Your code goes here...
}
}
Now u can access that from ur mainclass like 现在你可以从你的主类访问它了
App app= null;
app.x= 6;
app.printme();
As mentioned earlier, it's because you declared the variable but never instantiated it, meaning it does not exsist yet, it's just a placeholder for the type defined at the declaration, what you need to do is 如前所述,这是因为您声明了变量但从未实例化它,这意味着它尚不存在,它只是声明中定义的类型的占位符,您需要做的是
Leen x; // declare the variable
x = new implementationClass(); // instantiate the variable
x.PrintName(); // then you functions
Now since the interface is used, all functions on the interface is available, but the code will attempt to use the implementation form whatever class implemented the interface and was intantiated 现在,由于使用了接口,因此接口上的所有功能都可用,但是代码将尝试使用实现形式,无论实现接口并实例化的任何类
Why is this smart ? 为什么这很聪明? well say you lave a
List<Leen>
then all elements in the list can use the functions on Leen
regardless of what implementation of Leen
they were created with 好吧,如果您喜欢
List<Leen>
那么列表中的所有元素都可以使用Leen
上的函数,而与创建Leen
实现无关
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.