Constructor is executed when _____.

By Priyanshu Vaish|Updated : June 29th, 2022

Constructor is executed when _____.

  1. An object is created
  2. An object is used
  3. A class is declared
  4. An object goes out of scope

Answer: A. An object is created

Constructor is executed when an object is created.

Solution

Constructor is a unique method is responsible for creating the object.

A new keyword is immediately followed by the execution of the function Object depending on the type and parameters, a different function Object() is run.

Example:

Animal dog = new Animal()

Here new will call the default constructor of Animal

Animal dog = new Animal(“pluto”,”dog”);

Here new will call the Animal constructor has two parameters say name and type

The superclass constructor can be called by the subclass constructor in inheritance, but this must be the first statement in the definition of the subclass constructor.

The parent class's constructor is called using the super keyword.

For example, the code is:

class Animal{ 

Animal(){ 

System.out.println("I am an Animal"); 

}

class Dog extends Animal{ 

Dog(){ 

super(); 

System.out.println("I am a Dog"); 

}

class Main{ 

public static void main(String[] args){ 

Dog myDog=new Dog(); 

}

/* 

Output: 

I am an Animal 

I am a Dog 

*/ 

The first parent constructor will get called and then the child constructor.

☛ Related Questions:

Comments

write a comment

Follow us for latest updates