简体   繁体   English

无效的方法声明,需要返回类型

[英]Invalid method declaration, return type required

I am getting an error at public Rectangle(double width, double height){ saying that it's an invalid method declaration, return type required.我在 public Rectangle(double width, double height){ 收到一个错误,说它是一个无效的方法声明,需要返回类型。 I'm not sure how to fix it.我不知道如何解决它。 These are also my instructions for my assignment: Write a super class encapsulating a rectangle.这些也是我的作业说明:编写一个封装矩形的超类。 A rectangle has two attributes representing the width and the height of the rectangle.矩形有两个属性,分别代表矩形的宽度和高度。 It has methods returning the perimeter and the area of the rectangle.它有方法返回矩形的周长和面积。 This class has a subclass, encapsulating a parallelepiped, or box.这个类有一个子类,封装了一个平行六面体或盒子。 A parallelepiped has a rectangle as its base, and another attribute, its length.平行六面体以矩形为底,还有另一个属性,即长度。 It has two methods that calculate and return its area and volume.它有两种计算和返回其面积和体积的方法。

`public class Rectangle1
{

private double width;
private double height;

public Rectangle1(){
}

public Rectangle(double width, double height){
this.width = width;
this.height = height;

}

public double getWidth(){
return width;
}

public void setWidth(double width) {
this.width = width;

}


public double getHeight(){
return height;

}

public void setHeight(double height){
this.height = height;

}

public double getArea(){
return width * height;
}

public double getPerimeter(){
return 2 * (width + height);

}

}



public class TestRectangle {

public static void main(String[] args) {

Rectangle1 rectangle = new Rectangle1(2,4);

System.out.println("\nA rectangle " + rectangle.toString());
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " +
rectangle.getPerimeter());
}
}`

Constructor name should be same as your class name .构造函数名称应与您的类名称相同。 your class name is Rectangle1 thus your Constructor name should be the same as well, currently java compiler this it as an method without a return type , thus it complains .您的类名是Rectangle1因此您的Constructor name应该相同,目前java编译器将此它作为没有返回类型方法,因此它会抱怨

public Rectangle(double width, double height){

should be应该

public Rectangle1(double width, double height){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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