Home Tutorial Java Core Java Constructors

 
 

Share on Google+Share on Google+
Java Constructors
Posted on: November 20, 2012 at 12:00 AM
Advertisement
In this tutorial we will discuss in java constructor and its type with example.

Java Constructors

In this tutorial we will discuss in java constructor and its type with example.

Constructors :

A constructor is a special kind of method that has the same name as the class itself. It enables an object to initialize itself when it is created.
There are two points to remember during creation of constructors-

  • Constructor name must be same as the class name.
  • It should not return a value not even void.

Types of Constructors :

Default Constructor :

Default constructor is used when you want to automatically initialize the object variable with some default values at the time of object instantiation. It may be initialize with default value zero or you may supply your own valid value or left blank the block.

Parameterized Constructor :

Parameterized constructor takes some arguments at the time of object creation. At the time of object instantiation, the parameterized constructor is explicitly invoked by passing certain arguments.

Example :

class Sum {
int x, y;

// Default constructor
Sum() {
x = 12;
y = 22;
}

// Parameterized constructor
Sum(int a, int b) {
x = a;
y = b;
}

void displaySum() {
int sum;
sum = x + y;
System.out.println("Sum of two integers : " + sum);
}
}

public class ConstructorExample {
public static void main(String[] args) {
Sum sum1 = new Sum(); // Calling default constructor
Sum sum2 = new Sum(40, 39); // Calling parameterized constructor

sum1.displaySum();
sum2.displaySum();
}
}

Description : In this example, we have defined two constructors, one is default constructor and another is parameterized constructor. In the default constructor, we have initialized the value of class variables x and y to 12 and 22 respectively. While in parameterized constructor, we have passed two parameters a and b which is set equal to the class variables x and y. Now, to display the sum of two numbers, we have created a method displaySum() that calculates the addition of two numbers x and y. In the main method we have created two objects of same class with different constructors and invoke method with both objects and display the sum.

Output :

Sum of two integers : 34
Sum of two integers : 79
Advertisement

Related Tags for Java Constructors:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 20, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com