HOW DO I CALL ONE CONSTRUCTOR FROM ANOTHER IN JAVA?

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
Java 
 1143  View(s)
Ratings:
Rate this:
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)?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How do I call one constructor from another in Java?

    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.

    In Java another constructor of the same class can be called from a constructor via this(). Note however that this has to be on the first line.

    public class MyClass {
      public MyClass(double argument1, double argument2) {
        this(argument1, argument2, 0.0);
      }
      public MyClass(double argument1, double argument2, double argument3) {
        this.argument1 = argument1;
        this.argument2 = argument2;
        this.argument3 = argument3;
      }
    }
    That this has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:

    public class MyClass {
      public MyClass(double argument1, double argument2) {
        this(argument1, argument2, getDefaultArg3(argument1, argument2));
      }
      public MyClass(double argument1, double argument2, double argument3) {
        this.argument1 = argument1;
        this.argument2 = argument2;
        this.argument3 = argument3;
      }
      private static double getDefaultArg3(double argument1, double argument2) {
        double argument3 = 0;
        // Calculate argument3 here if you like.
        return argument3;
      }
    }

    There is also the "Instance initialization block" that gets executed always and before any other constructor is called. It consists simply of a block of statements "{ ... }" somewhere in the body of your class definition. There is also a "static"version of this to initialize static members: "static { ... }"


Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!