Difference between Constructor and Method
Note that the constructors and methods are not the same, though they look alike.
- A constructor does not return any value, whereas a method may return a value.
- The name of the constructor should be the same as the class name, whereas a method name can be the same as the class name.
- Constructors are not considered as members of the class.
Let us check whether a method can be named by class name.
ComplexNum.java
Constructor in Detail
Let us start with another example of Employee class. The class contains a set of attributes, It does not contain any method or constructors. Hence, if you create an object of this class, the attributes will be set by default values. Though this class does not have any constructor, an instance of the class can be created.
Note that if a class does not have any constructor, a default constructor is provided by the language.
Employee.java
TestMain.java
A constructor can be created by setting some values to the attributes. For example, if we want to set designation with Trainee
, we have to define a constructor. Thus, the above class can be redefined as follow:
Employee.java
Parameterized Constructor
Thus, if you want to create an object with some values of the attributes (not default values), you have to create a constructor.
Now, look at the following example, where a constructor is created. Here, the parameters of the constructor are passed at the time of creating an instance of the class.
Employee.java
TestMain.java
Remember that the default constructor is provided if the class does not contain any constructor.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.