Object.clone方法调用产生堆栈溢出错误

时间:2018-09-22 02:53:35

标签: java

嘿,我在尝试在我的代码中实现clone()方法时遇到了一些麻烦,这是有问题的代码

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.\n", test.sideLength, test.perimiter, test.area);
      Octagon clone = test.clone();
      System.out.println("Octagon cloned.");
      if (test.compareTo(test) == true)
      System.out.println("The octagons are identical");
      else
      System.out.println("The octagons are not identical");
   }
}

abstract class GeometricObject {
   double area;
   double perimiter;
}

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 Octagon clone(){
      return this.clone();
   }
   public boolean compareTo(Octagon x) {
      if (this.sideLength == x.sideLength)
         if (this.perimiter == x.perimiter)
            if (this.area == this.area)
               return true;
            else
               return false;
         else
            return false;
      else
         return false;
   }
}

这是我得到的控制台输出,

Enter side length of Octagon: 
8
The octagon has a side length of 8.00, a perimiter of 64.00, and an area of 309.02.
Exception in thread "main" java.lang.StackOverflowError
    at Octagon.clone(Lab2B.java:32)

它会重复很长一段时间的最后一行...我对java还是很陌生,这是我第一次尝试实现clone方法。从到目前为止我在网上搜索中看到的内容来看,我认为我拥有了我应该拥有的所有东西,但是我对此感到非常困惑。谁能指出我正确的方向?

1 个答案:

答案 0 :(得分:1)

“返回this.clone()”

clone方法中的

是递归调用。您的函数正在调用自身并返回该值,这会重复到堆栈溢出