By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
462,393 Members | 522 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 462,393 IT Pros & Developers. It's quick & easy.


P: 1
suppose in a program we have two constructor namely default nd parameterized 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
Sep 9 '14 #1
Share this Question
Share on Google+
4 Replies

P: 107
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.

Sep 19 '14 #2

Expert 100+
P: 785
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)

Expand|Select|Wrap|Line Numbers
  1. class A()
  2. {
  3.  public A(int i)
  4.  {
  5.   System.out.println("Inside 1");
  6.  }
  7.  public A()
  8.  {
  9.   this(0);
  10.   System.out.println("Inside 2");
  11.  }
  12. }
Sep 22 '14 #3

P: 1
You don't have to create two objects to access both constructors. The constructor that is called is determined by the parameters you include when you create the object. If no parameter is included the default constructor is called.
Oct 4 '14 #4

P: 43
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.

Expand|Select|Wrap|Line Numbers
  1. public class MyClass{
  2.    //This is the constructor
  3.    MyClass(){
  4.    }
  5.    ..
  6. }
Jul 7 '20 #5

Post your reply

Sign in to post your reply or Sign up for a free account.