suppose in a program we have two constructor namely default nd parameterized constructor..my doubt is in the main program why we have to create two objects to access the 2 constructors ???instead why not single object to acess to any number of constructors??? sorry if it a lame doubt
constructor
Collapse
X
-
Tags: None
-
A constructor that have no parameter is known as default constructor.
A constructor that have parameters is known as parameterized constructor
Why we use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Thanks
Raju -
You don't have to create 2 objects to access the two constructors.
A single object is enough, which is created running either through the first or second constructor, or both (see code below)
Code:class A() { public A(int i) { System.out.println("Inside 1"); } public A() { this(0); System.out.println("Inside 2"); } }Comment
-
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
Constructor has same name as the class and looks like this in a java code.
Code:public class MyClass{ //This is the constructor MyClass(){ } .. }Comment
Comment