我们现在正在学习如何在 Java
中使用多个类,并且有一个项目询问创建一个类 Circle
它将包含一个 radius
和 diameter
,然后从主类中引用它以查找直径。此代码继续收到错误(在标题中提到)
public class Circle
{
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
感谢您的帮助,-AJ
更新 1 :好的,但我不应该将第三行 public CircleR(double r)
声明为双精度,对吗?在我正在学习的书中,这个例子并没有做到这一点。
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
//This is a method. It performs some action (in this case it calculates the
//area of the circle and returns it.
public double area( ) //area method
{
double a = Math.PI * radius * radius;
return a;
}
public double circumference( ) //circumference method
{
double c = 2 * Math.PI * radius;
return c;
}
public double radius; //This is a State Variable…also called Instance
//Field and Data Member. It is available to code
// in ALL the methods in this class.
}
如您所见,代码 public Circle(double r)....
与我在 public CircleR(double r)
中所做的有什么不同?无论出于何种原因,书中的代码都没有给出错误,但是我说那里有错误。
原文由 Alex G 发布,翻译遵循 CC BY-SA 4.0 许可协议
当定义一个类的构造函数时,它们应该与它的类同名。因此下面的代码
是正确的,而您的代码
是错误的,因为您的构造函数与其类的名称不同。您可以遵循书中相同的代码并将构造函数从
至
或者(如果您真的想将构造函数命名为 CircleR)将您的类重命名为 CircleR。
所以你的新课应该是
正如 Froyo 和 John B 所指出的,我还在您的方法中添加了返回类型 double。
请参阅 这篇 关于构造函数的文章。
HTH。