+ 2
Can we call a constructor through the another constructor from the same class(like function calling) in java?
If yes then How?
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
}
}
+ 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;
}
}