java - 关于java的各种构造函数和参数
问题描述
我已经写了下面的说明,直到现在,我已经想出了两个参数并让方法分配值并检索它。但是,我必须遵循的指令之一是包含一个不带参数的构造函数,所以我想知道我应该在不带任何参数的构造函数中创建什么语句。如果有人给出指示,那就太好了。这是我到目前为止提出的代码。
public class Rectangle {
//first constructor no parameters
//public<class name> (<parameters>)<statements>}
//two parameters one for length, one for width
//member variables store the length and the width
//member methods assign and retrieve the length and width
//returning the area and perimeter
static int recPerimeter(int l, int w) {
return 2*(l+w);
}
static int recArea(int l, int w) {
return l*w;
}
public static void main(String[] args) {
int p = recPerimeter(5, 3);
System.out.println("Perimeter of the rectangle : " + p);
int a = recArea(5,3);
System.out.println("Area of the rectangle : " + a);
}
}
解决方案
First off, I would take some time to read the java tutorials. At least the "Covering the Basics"
There is a ton wrong with your example. You should store the the attributes of a rectangle - width and length as data members of the class which will get initialized with values through the constructors. If a default constructor is called with no values, then set the attributes to whatever you want. I set them to zero in the example. Also, you need to normally create an instance of your class and then access it. Big red flag if you are having to prepend "static" to everything.
public class Rectangle {
private int recLength;
private int recWidth;
public Rectangle() {
recLength = 0;
recWidth = 0;
}
public Rectangle( int l, int w ) {
recLength = l;
recWidth = w;
}
public int calcPerimeter() {
return 2*(recLength+recWidth);
}
public int calcArea() {
return recLength*recWidth;
}
public static void main (String [] args) {
Rectangle rec = new Rectangle(5,3);
System.out.println("Perimeter = "+ rec.calcPerimeter());
System.out.println("area = " + rec.calcArea());
}
}
推荐阅读
- java - Java - 将值输入 JTextArea 后事件之间的延迟
- java - 尝试编写一个函数以在发生错误时返回 false
- raku - 在 Raku 中混合私有和公共属性和访问器
- tvos - tvOS 究竟何时清除数据?
- r - 如何在基于向量的数据框中插入一列?
- pagination - Splunk - 添加分页
- javascript - 为什么我的提示计算器代码返回 NaN?
- sql - Oracle SQL - 未来日期/雇主年龄问题
- java - 将 Java 程序连接到 MySQL 中的数据库时出现 MySQLNonTransientConnectionException
- uwp - UWP 项目中的多目标库