Reputation: 121
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.
Upvotes: 0
Views: 1967
Reputation: 14746
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.
Upvotes: 1
Reputation: 139
It's called Constructor Chaining. It occurs through the use of inheritance. A subclass constructor method's ALWAYS call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.
There could be any number of classes in an inheritance chain. Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.
You may refer to https://www.thoughtco.com/constructor-chaining-2034057
Upvotes: 1