Where should I create a constructor, and where shouldn't I?

My first class in object oriented programming.

Should I create a constructor method for each class?

eg

public class Cube2 {

    int length;
    int breadth;
    int height;
    public int getVolume() {
        return (length * breadth * height);
    }
    Cube2() {
        this(10, 10);
        System.out.println("Finished with Default Constructor");
    }
    Cube2(int l, int b) {
        this(l, b, 10);
        System.out.println("Finished with Parameterized Constructor having 2 params");
    }
    Cube2(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
        System.out.println("Finished with Parameterized Constructor having 3 params");
    }
    public static void main(String[] args) {
        Cube2 cubeObj1, cubeObj2;
        cubeObj1 = new Cube2();
        cubeObj2 = new Cube2(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
        System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
    }
}

If I want to create a new constructor, should I use the same parameters that were used in the previous (first)?

as a constructor it Cube2(int l, int b, int h)has the same value with parameters for this Cube2(int l, int b)in addition to the variable (int h)

+3
source share
6 answers

There are many cases when a constructor is not needed, in particular if you plan to use a control inversion , where one requires a default constructor.

, sence two . , / , , .

, , , sensible defaults. timeout tcp.

+4

, , .

, yout : -— no-op — (super()).

— — : , ; , .

, (, private), . , factory — , , , . .

, " " . " ", , .

+3

, , . , , - , .

, , . , , . , , .

+2

, . API . , , , .

, , , , .

. - , , - . , , no-args.

+2

, , , - , ( ).

() , :

    public class Cube {
    Cube(){}
    }
+1

Constructor . Constructor , Constructor.

-1
source

Source: https://habr.com/ru/post/1794787/


All Articles