[英]Interface and extending
在如何使用以下代码甚至可能的情况下遇到问题。 我是新来的。 我有以下内容:
变量。java
public interface variables extends library{
public int func1(String a, String b);
public int func2(String a, String b);
}
调用变量.java
public CallVariables extends variables{
String hi = "Hi";
String by = "Bye";
//Then here somehow call my variables.java and be able to use it...
}
主.java
// Now, here I want to be able to actually call the first or either the second .java class.
// Is this possible? If yes, then how?
我想知道这是否可能,如果可以,请包括和示例。
通过指定关键字“interface”来声明接口。 例如:
interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}
Java中的接口示例
这就是 class 实现接口的方式。 它必须提供在接口中声明的所有方法的主体,或者换句话说,您可以说 class 必须实现接口的所有方法。
class 实现了接口,但一个接口扩展了另一个接口。
interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}
class Demo implements MyInterface
{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
Output:
implementation of method1
我希望这可以更清楚地说明 class 如何与接口一起工作。
请遵循接口和 class 的命名约定。 class可以实现interafce,interface可以扩展另一个接口,class可以扩展一个class。 这可能会帮助您:
interface Library{}
//First variables.java:
interface Variables extends Library{
public int func1(String a, String b);
public int func2(String a, String b);
}
//Second call Variables.java
class CallVariables implements Variables{
String hi = "Hi";
String by = "Bye";
//Then here somehow call my variables.java and be able to use it...
@Override
public int func1(String a, String b) {
// TODO Auto-generated method stub
System.out.println("func1 says :"+hi);
return 1;
}
@Override
public int func2(String a, String b) {
// TODO Auto-generated method stub
System.out.println("func2 says :"+by);
return 2;
}
}
//Third main.java
//Now, here I want to be able to actually call the first or either the second .java class.
// Is this possible? If yes, then how?
public class Main{
public static void main(String[] args) {
Variables variables = new CallVariables();
variables.func1("a", "b");
variables.func2("c", "d");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.