Codecheck无法通过,Sphere类构造函数参数不匹配错误求助
Hey there! Let's break down this error and get your code passing Codecheck smoothly.
What the Error Is Telling You
The error messages spell out the core issue clearly:
/tmp/codecheck.rA4OvRYwJM/InterfaceTester.java:6: error: constructor Sphere in class Sphere cannot be applied to given types;
GeometricSolid shape = new Sphere(10);
^
required: no arguments
found: int
reason: actual and formal argument lists differ in length
In simple terms: When you try to create a Sphere object with new Sphere(10), you're passing an integer (likely the radius) — but your Sphere class doesn't have a constructor designed to accept an integer parameter. Right now, the only constructor available for Sphere is a no-argument one (either you explicitly wrote it, or Java automatically generated it because you didn’t define any constructors).
How to Fix It
You just need to add a constructor to your Sphere class that matches the argument you’re passing. Here’s a step-by-step fix:
- Open your
Sphereclass file. - Add a constructor that takes an
intparameter (for the radius, or whatever that10represents):
public class Sphere implements GeometricSolid { // Add a field to store the radius if you don't have one already private int radius; // This constructor accepts an int argument, matching your call in InterfaceTester public Sphere(int radius) { this.radius = radius; } // Optional: If you still need to create a Sphere without passing a value, add a no-arg constructor too public Sphere() { // Set a default radius, like 0 this.radius = 0; } // Don't forget to implement all methods required by the GeometricSolid interface! }
A Quick Java Constructor Reminder
- If you don’t write any constructors in a class, Java automatically provides a free no-argument constructor.
- Once you define any constructor (like the
intparameter one above), Java stops generating the default no-arg constructor. If you still need to usenew Sphere()elsewhere, you have to write that no-arg constructor yourself.
After making this change, your new Sphere(10) call will match the constructor you added, and the error should vanish.
内容的提问来源于stack exchange,提问作者Ray Ma

