gpt4 book ai didi

java - 调用接口(interface)方法,但返回类型无效?

转载 作者:行者123 更新时间:2023-12-02 10:47:24 24 4
gpt4 key购买 nike

我不想来这里问一个可能是愚蠢的问题,但我是一名编码学生,我的老师提供的关于接口(interface)主题的信息很少,但我有一个作业要到期,我正在做调用类正在实现的接口(interface)中的方法时出现问题。这是我正在制作的项目的代码

import java.util.Scanner;
public class Lab2B {
public static void main(String[] args) {
Octagon test = new Octagon();
System.out.printf("The octagon has a side length of %1.2f, a perimiter of %1.2f, and an area of %1.2f.", test.sideLength, test.perimiter, test.area);
}
}

abstract class GeometricObject {
double area;
double perimiter;
public GeometricObject() {

}
}

class Octagon extends GeometricObject implements Comparable, Cloneable {
double sideLength;
public Octagon() {
Scanner input = new Scanner(System.in);
System.out.println("Enter side length of Octagon: ");
this.sideLength = input.nextDouble();
this.area = ((2 + (4 / Math.sqrt(2))) * this.sideLength * this.sideLength);
this.perimiter = (this.sideLength * 8);
}

public void clone() {
System.out.println("I wish I knew how to code");
}
}


interface Cloneable {
public void clone();
}

它给了我这个错误

Lab2B.java:29: error: clone() in Octagon cannot override clone() in Object
public void clone() {
^
return type void is not compatible with Object

老实说,我不确定我在这里做错了什么,这似乎与我在互联网上找到的每个界面示例都一致。非常感谢任何帮助。

最佳答案

首先,您可以从 java 实现 Cloneable 接口(interface)(无需创建自己的接口(interface))。

此外,它有点奇怪,但克隆方法位于 Object 类中,需要重写。 (它应该在 Cloneable 中)。要覆盖克隆方法,您可以执行以下操作:

@Override
protected Object clone() throws CloneNotSupportedException {

}

这是关于使用克隆进行深浅复制的好读物:

https://howtodoinjava.com/java/cloning/a-guide-to-object-cloning-in-java/

关于java - 调用接口(interface)方法,但返回类型无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52452641/

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