13

I want to execute multiple constructor, while creating a single object. For example, I have a class definition like this-

public class Prg
{
    public Prg()
    {
        System.out.println("In default constructor");
    }
    public Prg(int a)
    {
        System.out.println("In single parameter constructor");
    }
    public Prg(int b, int c)
    {
        System.out.println("In multiple parameter constructor");
    }
}

And I am trying to achieve it by the following code -

public class Prg
{
    public Prg()
    {
        System.out.println("In default constructor");
    }
    public Prg(int a)
    {
        Prg();
        System.out.println("In single parameter constructor");
    }
    public Prg(int b, int c)
    {
        Prg(b);
        System.out.println("In multiple parameter constructor");
    }
    public static void main(String s[])
    {
        Prg obj = new Prg(10, 20);
    }
}

But in this case it is generating errors like -

Prg.java:11: error: cannot find symbol
            Prg();
            ^
  symbol:   method Prg()
  location: class Prg
Prg.java:16: error: cannot find symbol
            Prg(b);
            ^
  symbol:   method Prg(int)
  location: class Prg
2 errors

Thanks

CodeCrypt
  • 701
  • 2
  • 8
  • 20

5 Answers5

14

Use this() instead of Prg() in your constructors

Prasad Kharkar
  • 13,107
  • 3
  • 36
  • 55
Manuel Manhart
  • 4,065
  • 2
  • 22
  • 25
  • 1
    Oh, thanks. I was searching for keywords like super, to point the same class. But I didn't tried this. Now it's working. – CodeCrypt Sep 25 '13 at 08:19
6

Use this instead of Prg

    public Prg()
    {
        System.out.println("In default constructor");
    }
    public Prg(int a)
    {
        this();
        System.out.println("In single parameter constructor");
    }
    public Prg(int b, int c)
    {
        this(b);
        System.out.println("In multiple parameter constructor");
    }
Prasad Kharkar
  • 13,107
  • 3
  • 36
  • 55
5

use this keyword.Full running code is as follows

public class Prg
{
    public Prg()
    {
        System.out.println("In default constructor");
    }
    public Prg(int a)
    {
        this();
        System.out.println("In single parameter constructor");
    }
    public Prg(int b, int c)
    {
        //Prg obj = new Prg(10, 20);

this(b);        System.out.println("In multiple parameter constructor");
    }
    public static void main(String s[])
    {
        Prg obj = new Prg(10, 20);
    }
}
SpringLearner
  • 13,546
  • 20
  • 71
  • 113
3

You should use this statement.

e.g.

public Prg(int b, int c)
{
    this(b);
    System.out.println("In multiple parameter constructor");
}
Jayamohan
  • 12,469
  • 2
  • 26
  • 40
2

When calling other constructors Use this() instead of Prg()

Prasad Kharkar
  • 13,107
  • 3
  • 36
  • 55
ahmedalkaff
  • 315
  • 1
  • 3