1 interface MyInterface{ 2 void method(); 3 } 4 class Test6 implements MyInterface { 5 void method() 6 { 7 System.out.println("I am implemented now!"); 8 } 9 }
时间: 2024-03-25 07:35:59 浏览: 15
这段代码定义了一个接口MyInterface和一个实现该接口的类Test6。Test6类中实现了MyInterface接口中的抽象方法method(),在该方法中输出了一段信息。由于Test6类已经实现了MyInterface接口,所以可以通过Test6类来创建MyInterface类型的对象,并调用method()方法。
下面是一个示例代码,创建了一个Test6对象,并将其赋值给MyInterface类型的变量mi,然后调用该变量的method()方法:
```
MyInterface mi = new Test6();
mi.method(); // 输出"I am implemented now!"
```
这里利用了Java中的多态性,将Test6对象向上转型为MyInterface类型,从而可以通过MyInterface类型的变量来调用Test6类中实现的method()方法。
相关问题
@Override is not allowed when implementing interface method
这个错误通常表示你在实现接口方法时使用了 `@Override` 注释,但是这个注释在接口中是不允许的。在接口中,你只能实现方法,不能重写或覆盖方法。
如果你想在实现接口方法时使用 `@Override` 注释,你需要确保该方法在接口中有一个默认实现。在 Java 8 及更高版本中,接口可以包含具有默认实现的方法,这种方法可以在实现接口时重写和覆盖。例如:
```
public interface MyInterface {
default void myMethod() {
System.out.println("This is a default implementation.");
}
}
public class MyClass implements MyInterface {
@Override
public void myMethod() {
System.out.println("This is my implementation.");
}
}
```
在这个例子中,`MyInterface` 包含一个默认实现的 `myMethod` 方法。在 `MyClass` 中,我们使用 `@Override` 注释来重写并覆盖这个方法。
java创建接口interface,包含抽象方法method1、method2、method3以及常量PI值为3.14159。创建类test,实现interface接口中三个方法,三个方法分别输出:我是method1、我是method2、我是method3。 在主类main中实例化test,并将三个方法分别调用。
好的,下面是Java代码实现:
```java
interface MyInterface {
public abstract void method1();
public abstract void method2();
public abstract void method3();
public static final double PI = 3.14159;
}
class Test implements MyInterface {
public void method1() {
System.out.println("我是method1");
}
public void method2() {
System.out.println("我是method2");
}
public void method3() {
System.out.println("我是method3");
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
t.method1();
t.method2();
t.method3();
}
}
```
输出结果:
```
我是method1
我是method2
我是method3
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)