The Definition of Java Constructor
Constructor Definition (not authority): A method that creates an object. In the Java, constructors are instance methods with the same name as their class. It can only have accessibility modifiers,no return value.
- Every class shld have it's own constructor,can't be inherited from its base class.
- A class can have more than one constructor,but at least one. If not explicit define,compiler will auto priovide a constructor without arguments.Take care,once define a explicit construtor,compiler will not provide any default constructor.
- Constructor can't have a return value,if given a return value,this 'constructor' will become a common method which just have the same name with class. However,we could write the keyword 'return' like this : public A(){return;} ,it is allowable.
- When subclass call it's own constructor,compliler will auto add statement 'super()', so if baseclass do not have a non-argument constructor, will hint a compile time error.
- In the statement of constructor, we could use 'this()/super()' to call other constructors in itsself or its baseclass,be careful recursive invocation error. One more rule, 'this();' or 'super()' must be the first statement in the constructor. Obviously,this(); and super(); can't be called at the same time.
constructor initialization
- static variables (priority:baseclass,subclass)
- static initializer blocks (priority:baseclass,subclass, in the order of statement)
- instance variables,instance initializer blocks (baseclass)
- constructor (baseclass)
- instance variables,instance initializer blocks (subclass)
- constructor (subclass)