1.What is Constructor?
- A constructor is a special method whose task is to initialize the object of its class.
- It is special because its name is the same as the class name.
- They do not have return types, not even void and therefore they cannot return values.
- They cannot be inherited, though a derived class can call the base class constructor.
- Constructor is invoked whenever an object of its associated class is created.
2.How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.
3.Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.
4.What are the differences between Contructors and Methods?
|Purpose||Create an instance of a class||Group Java statements|
|Modifiers||Cannot be abstract, final, native, static, or synchronized||Can be abstract, final, native, static, or synchronized|
|Return Type||No return type, not even void||void or a valid return type|
|Name||Same name as the class (first letter is capitalized by convention) -- usually a noun||Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action|
|this||Refers to another constructor in the same class. If used, it must be the first line of the constructor||Refers to an instance of the owning class. Cannot be used by static methods.|
|super||Calls the constructor of the parent class. If used, must be the first line of the constructor||Calls an overridden method in the parent class|
|Inheritance||Constructors are not inherited||Methods are inherited|
5.How are this() and super() used with constructors?
- Constructors use this to refer to another constructor in the same class with a different parameter list.
- Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.