what's the point of java constructor?

后端 未结 7 1357
野趣味
野趣味 2021-01-07 15:24

So I\'m learning java. I\'m one month in and I just learned about constructors. But I don\'t see the whole purpose of creating one. Why and when would I ever want to use one

7条回答
  •  梦谈多话
    2021-01-07 15:32

    Constructors are used to initialize a class and give parameters to a class. What is important is that they let you set the class state on creation. This allows you to use specific instances of a class with different data field values instead of relying on purely static information. Take the following example:

    class Obj {
      private int state = 0;
    
      public Obj(int state) {
         this.state = state;
      }
    
      public Obj() {
         state = 1;
      }
    }
    

    Now in main (or wherever) you can have:

    Obj obj1 = new Obj();
    Obj obj2 = new Obj(2);
    

    The two objects have different states (one is at state 1, the other is at state 2). If you were relying on static methods and members, the objects would share one state and would not be independent of each other.

    It is also important to note that constructors (specifically the new keyword) allocate memory for a given object internally so you don't have to worry about using malloc and other memory management. So they are important in that sense as well.

提交回复
热议问题