How do I call one constructor from another in Java?

前端 未结 21 2511
不知归路
不知归路 2020-11-22 01:06

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 th

相关标签:
21条回答
  • 2020-11-22 01:15

    It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:

     public Omar(){};
     public Omar(a){};
     public Omar(a,b){};
     public Omar(a,b,c){};
     public Omar(a,b,c,d){};
     ...
    

    You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e

    0 讨论(0)
  • 2020-11-22 01:17

    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

    0 讨论(0)
  • 2020-11-22 01:18

    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(someValue). The call to super must be the first call in the constructor or you will get a compiler error.

    0 讨论(0)
  • 2020-11-22 01:19

    Originally from an anser by Mirko Klemm, slightly modified to address the question:

    Just for completeness: 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. You can even have more than one. You can't call them, but they're like "shared constructor" code if you want to reuse some code across constructors, similar to calling methods.

    So in your case

    { 
      System.out.println("this is shared constructor code executed before the constructor");
      field1 = 3;
    }
    

    There is also a "static" version of this to initialize static members: "static { ... }"

    0 讨论(0)
  • 2020-11-22 01:20

    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.

    0 讨论(0)
  • 2020-11-22 01:22

    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).

    0 讨论(0)
提交回复
热议问题