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
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);
}
}
Use this()
instead of Prg()
in your constructors
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With