I am a newbie to Java , please have a look at the below Code
//Parent Class
public class Abc {
Abc(){System.out.println("hiii");
}
}
//Child Class
public class CDE extends Abc{
@Test
public void Xyz(){
System.out.println("hi");
}
}
Output is coming as
hiii
hi
PASSED: Xyz
Please help , i am not sure why the constructor of parent class is getting called when i am not even using the new Keyword to create object.I have created two different classes in Eclipse.Same is not happening if i am creating main method in child class ie not using TestNG @Test annotation.
When you use a @Test
annotation from TestNG, here's what TestNG does, behind the scenes.
@Test
, @BeforeClass
etc.,) and orders them in the TestNG way (i.e., @BeforeSuite
, @BeforeTest
, @BeforeClass
, @Test
and so on)The reason why your base class constructor is being invoked, is due to TestNG instantiating your child class via reflection, which triggers the constructor chain up the inheritance ladder (Which is what is called Constructor Chaining)
You can test this theory by adding a constructor to your child class CDE
and adding a System.out.println
. You will see the print statement being executed.
When you do this via a main()
method, there's no reflection involved, because TestNG is not involved.