Home How do I call one constructor from another in Java?
Reply: 15

How do I call one constructor from another in Java?

ashokgelal
1#
ashokgelal Published in 2008-11-12 20:10:19Z

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?

Community
2#
Community Reply to 2017-05-23 12:34:53Z

Yes, it is possible:

public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

Zizouz212
3#
Zizouz212 Reply to 2013-06-20 12:24:50Z

Using this(args). The preferred pattern is to work from the smallest constructor to the largest.

public class Cons {

 public Cons() {
  // A no arguments constructor that sends default values to the largest
  this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
 }

 public Cons(int arg1, int arg2) {
  // An example of a partial constructor that uses the passed in arguments
  // and sends a hidden default value to the largest
  this(arg1,arg2, madeUpArg3Value);
 }

 // Largest constructor that does the work
 public Cons(int arg1, int arg2, int arg3) {
  this.arg1 = arg1;
  this.arg2 = arg2;
  this.arg3 = arg3;
 }
}

You can also use a more recently advocated approach of valueOf or just "of":

public class Cons {
 public static Cons newCons(int arg1,...) {
  // This function is commonly called valueOf, like Integer.valueOf(..)
  // More recently called "of", like EnumSet.of(..)
  Cons c = new Cons(...);
  c.setArg1(....);
  return c;
 }
} 

To call a super class, use super(asdf). The call to super must be the first call in the constructor or you will get a compiler error.

Kaamel
4#
Kaamel Reply to 2013-04-23 23:12:24Z

When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:

class MyClass {
   int field;


   MyClass() {
      init(0);
   } 
   MyClass(int value) {
      if (value<0) {
          init(0);
      } 
      else { 
          init(value);
      }
   }
   void init(int x) {
      field = x;
   }
}

But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example

class MyClass {
   int field;

   MyClass(int value) {
      if (value<0)
         field = 0;
      else
         field = value;
   }
   MyClass() {
      this(0);
   }
}
olovb
5#
olovb Reply to 2015-05-07 22:52:03Z

As everybody already have said, you use this(…), which is called an explicit constructor invocation.

However, keep in mind that within such an explicit constructor invocation statement you may not refer to

  • any instance variables or
  • any instance methods or
  • any inner classes declared in this class or any superclass, or
  • this or
  • super.

As stated in JLS (§8.8.7.1).

amila isura
6#
amila isura Reply to 2016-02-12 01:50:32Z

Within a constructor, you can use the this keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.

Here's another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(1, 1);
    }
    public Rectangle(int width, int height) {
        this( 0,0,width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

}

This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.

ABHISHEK RANA
7#
ABHISHEK RANA Reply to 2015-11-27 19:01:24Z

You can a constructor from another constructor of same class by using "this" keyword. Example -

class This1
{
    This1()
    {
        this("Hello");
        System.out.println("Default constructor..");
    }
    This1(int a)
    {
        this();
        System.out.println("int as arg constructor.."); 
    }
    This1(String s)
    {
        System.out.println("string as arg constructor..");  
    }

    public static void main(String args[])
    {
        new This1(100);
    }
}

Output - string as arg constructor.. Default constructor.. int as arg constructor..

Akash Manngroliya
8#
Akash Manngroliya Reply to 2016-10-25 05:50:13Z

Yes it is possible to call one constructor from another with use of this()

class example{
   private int a = 1;
   example(){
        this(5) //here another constructor called based on constructor argument
        System.out.println("number a is "+a);   
   }
   example(int b){
        System.out.println("number b is "+b);
   }
Utsav
9#
Utsav Reply to 2016-11-16 16:14:17Z

Yes, any number of constructors can be present in a class and they can be called by another constructor using this()[Please do not confuse this() constructor call with this keyword].
this() or this(args) should be the first line in the constructor.

Example:
Class Test{
    Test(){
        this(10) // calls the constructor with integer args, Test(int a)
    }
    Test(int a){
        this(10.5) // call the constructor with double arg, Test(double a)
    }
    Test(double a){
        System.out.println("I am a double arg constructor");
    }
}

This is known as constructor overloading.
Please note that for constructor only overloading concept is applicable and not inheritance or overriding.

saikosen
10#
saikosen Reply to 2017-12-19 05:55:52Z

I will tell you an easy way

There are two types of constructors:

  1. Default constructor
  2. Parameterized constructor

I will explain in one Example

class ConstructorDemo 
{
      ConstructorDemo()//Default Constructor
      {
         System.out.println("D.constructor ");
      }

      ConstructorDemo(int k)//Parameterized constructor
      {
         this();//-------------(1)
         System.out.println("P.Constructor ="+k);       
      }

      public static void main(String[] args) 
      {
         //this(); error because "must be first statement in constructor
         new ConstructorDemo();//-------(2)
         ConstructorDemo g=new ConstructorDemo(3);---(3)    
       }
   }                  

In the above example I showed 3 types of calling

  1. this() call to this must be first statement in constructor
  2. This is Name less Object. this automatically calls the default constructor. 3.This calls the Parameterized constructor.

Note: this must be the first statement in the constructor.

S R Chaitanya
11#
S R Chaitanya Reply to 2017-01-07 13:27:36Z

Yes it is possible to call on constructor from another. But there is a rule to it. If a call is made from one constructor to another, then

that new constructor call must be the first statement in the current constructor

public class Product {
     private int productId;
     private String productName;
     private double productPrice;
     private String category;

    public Product(int id, String name) {
        this(id,name,1.0);
    }

    public Product(int id, String name, double price) {
        this(id,name,price,"DEFAULT");
    }

    public Product(int id,String name,double price, String category){
        this.productId=id;
        this.productName=name;
        this.productPrice=price;
        this.category=category;
    }
}

So something like below will not work.

public Product(int id, String name, double price) {
    System.out.println("Calling constructor with price");
    this(id,name,price,"DEFAULT");
}
J. Chomel
12#
J. Chomel Reply to 2017-03-03 09:50:18Z

Calling constructor from another constructor

class MyConstructorDemo extends ConstructorDemo
{
    MyConstructorDemo()
    {
        this("calling another constructor");
    }
    MyConstructorDemo(String arg)
    {
        System.out.print("This is passed String by another constructor :"+arg);
    }
}

Also you can call parent constructor by using super() call

Community
13#
Community Reply to 2017-05-23 12:02:58Z

The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.

Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.

Setter methods or constructors

Rodney P. Barbati
14#
Rodney P. Barbati Reply to 2017-11-13 23:01:22Z

There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.

With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.

class LambdaInitedClass {

   public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
       init.accept(this);
   }
}

Call it with...

 new LambdaInitedClass(l -> { // init l any way you want });
GetBackerZ
15#
GetBackerZ Reply to 2017-11-21 14:03:51Z

Pretty simple

public class SomeClass{

    int number;
    String someString;

    public SomeClass(){
        number = 0;
    }

    public SomeClass(int number){
        this(); //set the class to 0
        this.setNumber(number); 
    }

    public SomeClass(int number, String someString){
        this(number); //call public SomeClass( int number )
    }

    public void setNumber(int number){
        this.number = number;
    }
    public void setString(String someString){
        this.someString = someString;
    }
    //.... add some accessors
}

now here is some small extra credit:

public SomeOtherClass extends SomeClass {
    public SomeOtherClass(int number, String someString){
         super(number, someString); //calls public SomeClass(int number, String someString)
    }
    //.... Some other code.
}

Hope this helps.

Paul Chu
16#
Paul Chu Reply to 2018-02-13 14:05:23Z

I know there are so many examples of this question but what I found I am putting here to share my Idea. there are two ways to chain constructor. In Same class you can use this keyword. in Inheritance, you need to use super keyword.

    import java.util.*;
    import java.lang.*;

    class Test
    {  
        public static void main(String args[])
        {
            Dog d = new Dog(); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
            Dog cs = new Dog("Bite"); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.

            // You need to Explicitly tell the java compiler to use Argument constructor so you need to use "super" key word
            System.out.println("------------------------------");
            Cat c = new Cat();
            Cat caty = new Cat("10");

            System.out.println("------------------------------");
            // Self s = new Self();
            Self ss = new Self("self");
        }
    }

    class Animal
    {
        String i;

        public Animal()
        {
            i = "10";
            System.out.println("Animal Constructor :" +i);
        }
        public Animal(String h)
        {
            i = "20";
            System.out.println("Animal Constructor Habit :"+ i);
        }
    }

    class Dog extends Animal
    {
        public Dog()
        {
            System.out.println("Dog Constructor");
        }
        public Dog(String h)
        {
            System.out.println("Dog Constructor with habit");
        }
    }

    class Cat extends Animal
    {
        public Cat()
        {
            System.out.println("Cat Constructor");
        }
        public Cat(String i)
        {
            super(i); // Calling Super Class Paremetrize Constructor.
            System.out.println("Cat Constructor with habit");
        }
    }

    class Self
    {
        public Self()
        {
            System.out.println("Self Constructor");
        }
        public Self(String h)
        {
            this(); // Explicitly calling 0 args constructor. 
            System.out.println("Slef Constructor with value");
        }
    }
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.334712 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO