+ 2

Can we call a constructor through the another constructor from the same class(like function calling) in java?

If yes then How?

30th Mar 2017, 5:27 PM
Giriraj Nagar
Giriraj Nagar - avatar
2 Answers
+ 2
public class A { public A ( ) { System.out.println ( "Default constructor" ) ; } public A ( int i ) { this ( ) ; System.out.println ( i ) ; } public static void main ( String [ ] args ) { A a = new A ( 5 ) ; // Default constructor // 5 } }
30th Mar 2017, 5:58 PM
K.C. Leung
K.C. Leung - avatar
+ 2
Yes you can. It must be the first call made though. You just use the this keyword and match the signature of the constructor you wish to call. class MyClass { int count; MyClass() { this(42); // More code... } MyClass(int count) { this.count = count; } }
30th Mar 2017, 6:02 PM
ChaoticDawg
ChaoticDawg - avatar