what's the point of java constructor?

后端 未结 7 1287
野趣味
野趣味 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:47

    Actually constructor is needed IF you need to assign unique initial state to an instance of a class. In Java i only just realized (by a friend) that we can do this:

    public class MyClass1 {
         private class MyClass2 {}
         private MyClass2 myobj2 = new MyClass2();
    }
    

    So no need for implicit constructor. But if something like follows, you need constructor.

    public class MyClass1 {
         private class MyClass2 { 
             private int id_ = 0;
             public MyClass2(int id) { id_ = id; }    // how to reach this?   
         }
    
         private MyClass2 myobj2 = new MyClass2(1);   // (this doesn't work. Not unique)
    
         public MyClass1(int id)     { myobj2 = new MyClass2(id); }   // by this!
    }
    MyClass1 obj1 = new MyClass1(100);
    MyClass1 obj2 = new MyClass1(200);
    
    0 讨论(0)
提交回复
热议问题