0

Can we call a method inside a constructor?

hw it is possible?

12th Aug 2017, 6:21 PM
Pavi Mohan
Pavi Mohan - avatar
2 Antworten
+ 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.
12th Aug 2017, 6:31 PM
Dev
Dev - avatar
0
tq
12th Aug 2017, 6:34 PM
Pavi Mohan
Pavi Mohan - avatar