Reputation: 3
I hate to come one here and ask what is probably a stupid question, but I'm a coding student and my teacher has offered very little information on the subject of interfaces but I have an assignment due, and I'm having a problem calling a method within an interface that a class is implementing. Here is the code of the project I am making
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();
}
and its giving me this error
Lab2B.java:29: error: clone() in Octagon cannot override clone() in Object
public void clone() {
^
return type void is not compatible with Object
I'm honestly not sure what I am doing wrong here, this seems to be in line with every example of an interface that I can find on the internet. Any help is greatly appreciated.
Upvotes: 0
Views: 55
Reputation: 83527
First you should not declare a Cloneable
interface. This already exists in the standard Java API.
However, unless implementing Cloneable
is specifically required by your assignment, you should remove it from your code. The Cloneable
interface's design is considered broken by modern Java standards. It only exists because of legacy code that was written when Java was first invented.
Upvotes: 0
Reputation: 6524
First, you can implement Cloneable interface from java( no need to create your own).
Also, its a bit weird but clone method is in Object class which needs to be overriden. (It should have been in Cloneable). To override clone method, you can do something like this:
@Override
protected Object clone() throws CloneNotSupportedException {
}
Here is a good read on Deep and Shallow Copy using clone:
https://howtodoinjava.com/java/cloning/a-guide-to-object-cloning-in-java/
Upvotes: 1