bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Java Constructors

 

Constructor is a type of method which is used to initialize the object that called at the time of object creation.

To create constructor, constructor name should be same as class name and also does not use explicit return type in case of constructor.

 

Types of Java Constructors

There are two types of java constructors:

  1. Default constructor
  2. Parameterized constructor

 

1. Default constructor – A constructor which have no parameter is known as default constructor.

Syntax

<class_name>(){

}

Example

public class Addition

{

Addition()  // default constructor

{

System.out.println("Addition Constructor");

}

public static void main(String args[]){

Addition ad=new Addition (); // Automatically default constructor is called

}

}

Output

Addition Constructor

 

2. Parameterized Constructor – A constructor which contains parameters is known as parameterized constructor.

Syntax

<class_name>(Parameter_list){

}

Example

public class Addition

{

int c;

Addition(int a, int b)  // parameterized constructor

{

c = a + b;

System.out.println("Addition of two numbers:"+c);

}

public static void main(String args[]){

Addition ad=new Addition (20,40); }

}

Output

Addition of two numbers: 60

 

Difference between Constructor and Method:

Java Constructor Java Method
Constructor name must be same as the class name. Method name may or may not be same as class name.
It is invoked implicitly Method is invoked explicitly.
It does not contain any return type. It must contain return type.
The java compiler provides a default constructor if you do not contain any constructor. It is not provided by compiler.
It initializes the state of an object. It exposes behavior of an object.

"0 Responses on Java Constructors"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 04th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Java Constructors.