14

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
  • 711
  • 2
  • 8
  • 20

5 Answers5

14

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

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
Manuel Manhart
  • 4,819
  • 3
  • 24
  • 28
  • 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,410
  • 5
  • 37
  • 56
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,738
  • 20
  • 78
  • 116
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,734
  • 2
  • 27
  • 41
2

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

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
ahmedalkaff
  • 313
  • 1
  • 3