Soumyansh Gupta
Soumyansh Gupta

Reputation: 121

@Test is calling Parent class constructor in TestNG Selenium

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

Answers (2)

Krishnan Mahadevan
Krishnan Mahadevan

Reputation: 14746

When you use a @Test annotation from TestNG, here's what TestNG does, behind the scenes.

  • It first loads your class.
  • It makes a list of all TestNG annotated methods that are to be run (For e.g., @Test, @BeforeClass etc.,) and orders them in the TestNG way (i.e., @BeforeSuite, @BeforeTest, @BeforeClass, @Test and so on)
  • It finds a default constructor in your class. If no default constructor is found, it tries to look for a 1 argument constructor that takes a string.
  • Using reflection the class is now instantiated.
  • Now using the instance of your test class obtained via reflection, TestNG starts calling the various annotated methods in a pre-defined order.

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

Lal Ansari
Lal Ansari

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

Related Questions