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
- //Java Program to create and call a default constructor
- class Bike{
- //creating a default constructor
- Bike(){System.out.println("Bike is created");}
- //main method
- public static void main(String args[]){
- //calling a default constructor or creating object
- Bike b=new Bike();
- }
- }
Comments
Post a Comment