Sunday 7 February 2016

What is constructor in java

What is constructor in java:
======================
The main objective of constructor is to perform initialization of object.

When ever we create object the constructor is going to be executed automatically.

Syntax:
=======

constructorname()
{
;;
;;
}

Here constructor name should be same as our class name.

Rules for writing constructor:
========================
1.The name of the constructor and name of the class must be same
2.return type is not allowed for constructors even void also.
3.If we are declaring any return type for the constructor then it will be become a normal method.
4.The only applicable modifiers for constructors are:
        a. public
        b. private
        c. protected
        d. default
5.If we are using any other modifier we are going to get compile time error.
Example:
=========
package selenium.basics;

public class Student {
String name;
int id;

public Student(String name,int id) {
    this.name=name;
    this.id=id;   
}
public static void main(String[] args) {
    Student student = new Student("ramesh", 123);
    System.out.println("name is :" +student.name);
    System.out.println("id is :"+student.id);
   
    Student student1 = new Student("selenium", 456);
    System.out.println("name is :" +student1.name);
    System.out.println("id is :"+student1.id);
}
}



Defaullt Constructor:
==================
1. Every class in java including abstract class also contains constructor.
2. If we are not writing any constructor then compiler will always create default constructor.
3. If we are writing at least one constructor then compiler wont generate any default constructor.
4.Default constructor is always no argument constructor.
5.Access modifier of the default constructor is same as class modifier.
example of default constructor:
========================
package selenium.basics;

public class DefaultConstructorDemo {

    DefaultConstructorDemo()
    {
        System.out.println("default construcor");
    }
    public static void main(String[] args) {
       
        DefaultConstructorDemo demo = new DefaultConstructorDemo();
       
    }
}


Constructor over loading:
=====================
If a class contain more than one constructor then we can say it is constructor over loading.

Example:
=========
package selenium.basics;

public class Student {
String name;
int id;

public Student(String name,int id) {
    this.name=name;
    this.id=id;   
}

public Student() {
    System.out.println("default constructor");
}
public Student(int id)
{
    this.id=id;
}
public static void main(String[] args) {
    Student student = new Student("ramesh", 123);
    System.out.println("name is :" +student.name);
    System.out.println("id is :"+student.id);
   
    Student student1 = new Student("selenium", 456);
    System.out.println("name is :" +student1.name);
    System.out.println("id is :"+student1.id);
}
}

1 comment: