开发者

NoSuchMethodError when compiling the source code

开发者 https://www.devze.com 2023-04-11 23:07 出处:网络
class Box { double weight; double height; double depth; Box(Box ob){ weight = ob.weight; height = ob.height;
class Box {
  double weight;
  double height;
  double depth;

  Box(Box ob){
    weight = ob.weight;
    height = ob.height;
    depth = ob.depth;
  }

  Box(double w, double h, double d){
    weight = w;
    height = h;
    depth = d;
  }

  Box() {
    weight = -1;
    height = -1;
    depth = -1;
  }

  Box(double len){
    weight = height = depth = len;
  }

  double volume(){
    return weight * height * depth; 
  }
}

 public class OverloadConss {
    public static void main(String[] args) {
            Box mybox1 = new Box (15,20,10);
            Box mybox2 =  new Box ();
            Box mycube = new Box(7);
            Box myclone =  new Box (mybox1);
            double vol;
            vol = mybox1.volume();
            System.out.println("The volume of the first box: " + vol);
            vol = mybox2.volume();
            System.out.println("The volume of the second box: " + vol);
            vol = mycube.volume();
            System.out.println("The volume of the开发者_如何学Go mycube: " + vol);
            vol = myclone.volume();
           System.out.println("The clone of the mybox1:" + vol);
    }
}

When I compile the source code I got the message:

Java/Eclipse/Exception in thread "main" java.lang.NoSuchMethodError: Box.(LBox;)at OverloadConss.main(OverloadConss.java:33)


There is no problem with your code; I run it without any error in eclipse. Output:

The volume of the first box: 3000.0
The volume of the second box: -1.0
The volume of the mycube: 343.0
The clone of the mybox1:3000.0

What are you using to run the script? If you using eclipse; try rebuilding workspace or rewriting the files (copy + paste).

Note: I would use something like this for Box.java so you only has to change 1 constructor if you change the datastructur.

class Box {
  double weight;
  double height;
  double depth;

  Box(Box ob){
    this(ob.weight, ob.height, ob.depth);
  }

  Box(double w, double h, double d){
    weight = w;
    height = h;
    depth = d;
  }

  Box() {
    this(-1, -1, -1);
  }

  Box(double len){
    this(len, len, len);
  }

  // additional methods
}


You have to put different classes in different .java-files, and it should work.


If both classes are in the same file then I don't see how this can happen. OverloadConss.main is called a Box constructor that is defined.

If they are in two separate files then my guess is that you added Box.Box(Box) recently and have not recompiled Box.java after that. Java is able to access some Box class so you are not getting ClassNotFoundException

Your best bet is to delete all .class files and recompile.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号