首页 > 解决方案 > 关于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);
        }
}

标签: java

解决方案


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());
    }
}

推荐阅读