Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute multiple constructor, when creating single object [duplicate]

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

like image 360
CodeCrypt Avatar asked Sep 25 '13 08:09

CodeCrypt


3 Answers

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);
    }
}
like image 78
SpringLearner Avatar answered Nov 02 '22 06:11

SpringLearner


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

like image 31
Manuel Manhart Avatar answered Nov 02 '22 08:11

Manuel Manhart


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");
    }
like image 6
Prasad Kharkar Avatar answered Nov 02 '22 06:11

Prasad Kharkar