Comment puis-je appeler un constructeur d'un autre en Java

Mots clés : javaconstructorjava

meilleur 5 Réponses Comment puis-je appeler un constructeur d'un autre en Java

vote vote

94

public class Foo {     private int x;      public Foo() {         this(1);     }      public Foo(int x) {         this.x = x;     } } 
vote vote

90

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;     } } 
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;     } }  
vote vote

73

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;   } } 
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;    }  } 
vote vote

66

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

54

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;     }  } 

Questions similaires