what is constructor in OOPs?

     A constructor is a special type of method which gets executed automatically te movement we instantiated the a object on a class in C++ Java and C# whenever  we create a class it can have 2 types  of constructor 

1. zero parameter  

     Internal zero parameter implicit constructor 

2. Explicit 

     parameterized constructor

             implicit constructor will be there by  default whereas explicit constructor need to create by the programmer 

        Any  constructor by default is used to calculate an allocate the required amount of heap memory 

      Constructor are also used to assign the default values ir user defined values to the instance level variables 

   Other than these two works if programmer want automatically certain action to be done the movement we initialized on the class then that should coded explicit constructor

   In C++ java and C# if we created  a method under the same name which is the class name then automatically it will be treated as constructor by the compiler

Note: Constructors does't have any return type

  1. //Java Program to create and call a default constructor  
  2. class Bike{  
  3. //creating a default constructor  
  4. Bike(){System.out.println("Bike is created");}  
  5. //main method  
  6. public static void main(String args[]){  
  7. //calling a default constructor  or creating object  
  8. Bike b=new Bike();  
  9. }  
  10. }  

Comments

Blogs