constructor

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • diviii2594
    New Member
    • Sep 2014
    • 1

    constructor

    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
  • rajujrk
    New Member
    • Aug 2008
    • 107

    #2
    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

    Comment

    • chaarmann
      Recognized Expert Contributor
      • Nov 2007
      • 785

      #3
      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

      • Toppper
        New Member
        • Aug 2010
        • 1

        #4
        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.

        Comment

        • Sherin
          New Member
          • Jan 2020
          • 77

          #5
          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

          Working...