Why There is need of explicit constructor

What is the need of define a constructor under a class when we have an implicit constructor for creating the Instance?

Implicit constructor of a class will Initialized the variable of the class with default value or with a given value that is assign at the time of declaring a variable so, the drawback in this approach is whenever we create the Instance of the class the variable will be Initialized with the same value every time.

Suppose if we define a class First with variable ‘x’ in it Initialized with 100 so,if we create 3 Instances to the class in all the 3 Instances we will have a copy of ‘x’ that will be Initialized with the value 100.

                                 First f1 = new First (  );                     
                                 First f2 = new First (  );
                                 First f3 = new First (  );


To overcome the above problem if we define a parameterized constructor in the class we will get a chance of sending new values for x everytime the Instance is created.




No comments:

Post a Comment