In the previous tutorial, we have discussed about Constructor. We know that if a Constructor is not defined in a class, the language provides a constructor which assigns default values to the instance variables. Here, we will discuss that a class may contain more than one constructor. If you define multiple constructors, you should be careful about the parameters.
First, we will design multiple constructors in a class. Then we will discuss what can not be done.
Employee.java
TestMain.java
So, you do understand that multiple constructors can be defined in a class.
Now, look at the following code. It will not compile. Then try to understand why this class is not compiling?
This class contains two constructors with the same number of arguments
. Don't think that two constructors can not be defined by the same number of arguments. this class is not compiled because two constructors are conflicting
. In the last two constructors, the number of parameters are same and the sequence of data types is also the same. Hence, if these constructors are called, the runtime environment will not understand which one is to be called.
So, if you define two constructors with the same number of parameters, be careful. Those constructors should have a different sequence of data types as parameters.
Hope, you have the basic understanding about constructors. Now we may try to write a program multiple objects of the Employee class will be created.
Content of Emloyee.java
Content of TestMain.java
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.