code_junkie

How do I call one constructor from another in Java?

Nov 12th, 2011
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. public class Foo
  2. {
  3. private int x;
  4.  
  5. public Foo()
  6. {
  7. this(1);
  8. }
  9.  
  10. public Foo(int x)
  11. {
  12. this.x = x;
  13. }
  14. }
  15.  
  16. public class Cons {
  17. public Cons() {
  18. this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
  19. }
  20. public Cons(int arg1, int arg2) {
  21. this(arg1,arg2, madeUpArg3Value);
  22. }
  23.  
  24.  
  25. public Cons(int arg1, int arg2, int arg3) {
  26. // Largest constructor that does the work
  27. this.arg1 = arg1;
  28. this.arg2 = arg2;
  29. this.arg3 = arg3;
  30. }
  31. }
  32.  
  33. public class Cons {
  34. public static Cons newCons(int arg1,...) {
  35. // This function is commonly called valueOf, like Integer.valueOf(..)
  36. // More recently called "of", like EnumSet.of(..)
  37. Cons c = new Cons(...);
  38. c.setArg1(....);
  39. return c;
  40. }
  41. }
Add Comment
Please, Sign In to add comment