Sunday, 31 July 2016

Java default and parameterized constructors

A constructor is similar to a method that is used to initialize the instance variables. The sole purpose of a constructor is to initialize the instance variables. All objects that are created must be given initial values. Giving initial values to objects can be done using two approaches.


  • Using the dot operator to access the instance variable and them assign values to them individually.
  • The second method is with the help of method like getData() to initialize each object individually using statement like rect1.getData(10,10);
                  But, it would be simpler to initialize an object when it is first created. Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of constructors.

constructors initializes an object immediately upon creation. One the constructor is defined, the constructor is automatically called immediately after the object is created. A constructor has the following properties:

1. The constructor's name and class name should be same and the constructors name should be ended with a pair of simple braces.

 Ex: person ()
      {

        }

2. A constructor may have or may not have parameters. parameters are variables to receive data from
    outside into the constructor. If a constructor does not have any parameters, it is called default  constructor.If a constructor have one or more parameters, it is called parameterized constructor.

3. A constructor does not return any value, not even void
4. A constructor is automatically called and executed at the time of creating an object.
    Example:

                Person p1 = new  Person(); // here default constructor is called
                Person p2 = new Person("Raju", 22); // here parameterized constructor is called.
5.A constructor is called and executed only one per object, This means when we create an object, the
   constructor is called. When we create second object, again the constructor is called second time.

  The following program show how Java default and parameterized constructors works


import java.io.*;
import java.util.*;
class person
{
private String name;
private int age;
person()           // java default constructor used to initialize instance variables
{
name = "Raju";   
age = 22;
}

person (String s, int i)
{
name=s;
age=i;
}
void talk()
{
System.out.println(" Hello I am" +name);
System.out.println(" my age is" +age);
}
}
class Demo
{
public static void main( String args[])
{
person p1 = new person();
p1.talk();
person p2 = new person ( "sita", 20);
p2.talk();
}
}

      

0 comments:

Post a Comment

Advertisement

Find Us On Facebook

C Programming

More

C++ Tutorial

More

Java Tutorial

More

Computer Basics

More

MS Office

More

Database Management

More
Top