Constructors :
- Java constructors are the methods which are used to initialize objects.
- Constructor method has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly.
- Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially.
- It is optional to write constructor method in a class but due to their utility they are used.
- Constructor method doesn't specify a return type, they return instance of class itself.
- Default constructor provides the default values to the object like 0, null etc. depending on the type.
Java constructor overloading
Like other methods in java constructor can be overloaded i.e. we can create as many constructors in our class as desired. Number of constructors depends on the information about attributes of an object we have while creating objectsRules for creating java constructor
There are basically two rules defined for the constructor.- Constructor name must be same as its class name
- Constructor must have no explicit return type
Java Constructor | Java Method |
---|---|
Constructor is used to initialize the state of an object. | Method is used to expose behaviour of an object. |
Constructor must not have return type. | Method must have return type. |
Constructor is invoked implicitly. | Method is invoked explicitly. |
The java compiler provides a default constructor if you don't have any constructor. | Method is not provided by compiler in any case. |
Constructor name must be same as the class name. | Method name may or may not be same as class name. |
No comments:
Post a Comment