0
Can we call a method inside a constructor?
hw it is possible?
2 Answers
+ 11
Yes, you can, this is what constructors are for.
class A {
String str = null;
A() { //constructor
polymorphicMethod();
str = "class A string";
}
void polymorphicMethod(){
//do stuff
}
}
class B extends A{
int posOfLetterA = 0;
void polyMorphicMethod() { //overriden
posOfLetterA = str.indexOf("A"); //throws null pointer exception, str not created yet!!
}
}
But calling instance method in constructor is dangerous because the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on testability.
0
tq