简体   繁体   中英

Object.clone method call giving stack overflow error

Hey guys I'm having some trouble while trying to implement to clone() method in my code, here is the code in question

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

This is the console output I am getting,

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)

and it repeats the last line for a really long time... I'm still pretty new to java, and this is my first time trying to implement the clone method. From what I have seen so far online searching around I think I have everything I'm supposed to have but I'm really stumped on this. Can anyone point me in the right direction?

“return this.clone()”

in the clone method is a recursive call. Your function is calling itself and returning that value and this repeats into a stack overflow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM