1

I have a class which consist of three constructors ,my requiremt is that i want to call all of the constructors using one single object creation.Is it possible??

Lets say

 Class A{

        A(int a){
        }

        A(int a,int b){
        }

        A(int a,int b,int c){
        }

I want to call all the constructors using one object creation ,how to do that???

lucifer
  • 2,297
  • 18
  • 58
  • 100
  • 2
    Why would you want to do that? Potentially [related](http://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java). – 4nt Aug 21 '15 at 02:37
  • No. Each constructor creates its own instance. But the constuctors can share code, if that is what you are after. Also, in addition to constructors, there are instance initializer blocks. *All* of those are run in addition to the selected constructor. – Thilo Aug 21 '15 at 02:41
  • You can refer here: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html http://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java – Kenny Tai Huynh Aug 21 '15 at 02:50
  • BTW This is possible using Byte code generation, but I am assuming this is not what you had in mind. – Peter Lawrey Aug 21 '15 at 06:35

2 Answers2

5

Your constructors should be designed in such a way for that. Something like,

 Class A{

        A(int a){
            this(a, 0);
        }

        A(int a,int b){
            this(a, b, 0);
        }

        A(int a,int b,int c){
            // All logic here.
        }

You can't call multiple constructors from outside to construct a single object.

Codebender
  • 14,221
  • 7
  • 48
  • 85
2
Class A{
   A(){
     this(10);
     System.out.println("No Arg constructor");
   }
   A(int x){
     System.out.println("Int arg constructor");
   }
}
Class B extends A{
 public static void main (String arg[]){
   B b=new B();

 }
}

this() call to it's own overloaded constructor.this() is not add automatically we should add it manually.

amila isura
  • 1,050
  • 1
  • 16
  • 26