> What is constructor in java?

What is constructor in java?

Posted at: 2014-12-18 
Constructor is a method have same name like as class name. A Constructor is invoke when the object is created it does does not return any value.

For knowing what a contructor is, i assume you understand what a class and an object are. A constructor is essentially implicitly implied(one exists by default) and what this does is, whenever an object of a class is created, the constructor allocates the memory required for the class members.

Lets see an example here

public class Student

{

string strstudentName;

float flmarkinMaths;

float flMarkinScience;

float flMarkinSocialStudies;

/* A constructor called Student(); will be invoked when the object is created */

/* Noticed how it has the same name as the class? */

}

and in the calling method, when you create an object inside the main method, you will be creating an object of the student class like

student objStudent=new Student(); the constructor is invoked and begins allocating memory of the primitive members inside the class.

You can also use a constructor to initialize data members inside the class by using a parameterized constructor and then invoking the object with a parameter

Example: http://www.tutorialspoint.com/java/java_...

Constructor is a special type of method that is used to initialize the object.

Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

-Constructor name must be same as its class name

-Constructor must have no explicit return type

There are two types of constructors:

-default constructor (no-arg constructor)

-parameterized constructor

It is a method (a function) that creates (instantiates) an instance of an object in a class. The return value is a reference to the new object.

In more concrete terms, if you wanted to create an instance of a circle on the screen you would call the constructor to allocate storage for the data that describes the properties of the circle, such as the location (x and y) of the center, the radius, the color of the outline of the circle and the color of the inside of the circle.