gpt4 book ai didi

java - 接口(interface)及扩展

转载 作者:行者123 更新时间:2023-12-01 19:35:00 24 4
gpt4 key购买 nike

对于如何使用以下代码或者甚至可能使用有困难。我是新来的。我有以下内容:

变量.java

public interface variables extends library{
public int func1(String a, String b);
public int func2(String a, String b);
}

CallVariables.java

public CallVariables extends variables{
String hi = "Hi";
String by = "Bye";
//Then here somehow call my variables.java and be able to use it...
}

ma​​in.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”来声明的。例如:

interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}

Java 接口(interface)示例

这就是类实现接口(interface)的方式。它必须提供在接口(interface)中声明的所有方法的主体,或者换句话说,您可以说该类必须实现接口(interface)的所有方法。

类实现接口(interface),但接口(interface)扩展另一个接口(interface)。

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();
}
}

输出:

方法1的实现

我希望这能让我们更清楚地了解类如何与接口(interface)一起工作。

关于java - 接口(interface)及扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58175259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com