I was confused by constructor for many days , reading many code and books ,but still did not fully understand what constructor actually is. Could any one show what would happen without constructor in Java?
1 Answer
All classes have a constructor. If you don't specify one, you will get a default constructor with no parameters.
So when you do this:
class Test { } You will actually get this:
class Test { Test() { super(); // This is a call to the constructor of the Object class. } } The constructor lets you create instances of the class with the new keyword. Like this:
Test test = new Test(); // This calls the default constructor. If there weren't constructors in Java, you wouldn't be able to create objects.
Objectclass, so if you don't write a constructor on your class, you still have the one from theObjectclass. So ALL classes have a constructor.