Tuesday, October 4, 2011

Constructor

Constructor is used to show the behavior of the class and
it also use to create the object of the class.

Name of constructor is same as class name.

When we create object of class, constructor call automatically.

Constructor has no return type.

It show the behavior of class, so name of constructor is same as name of class.

"new" keyword is used to allocate memory for object.

When we don't define a constructor in our program then JVM provides default constructor.

Without parametrized constructor is default constructor.


In following Example constructor is used only to show the behavior of the Human class.

class Human
{
Human()
{
System.out.println("I am Human");
}
public static void main(String arg[])
{
new Human();
}
}

In following Example constructor is used to show the behavior of the Human class and also use to create the object of the Human class.

class Human
{
Human()
{
System.out.println("I am Human");
}
public static void main(String arg[])
{
Human h;
h=
new Human();
}
}


Note:
Human h;
h is reference of Human class. It has no memory.

h=new Human();
Here we used "new" keyword to allocate the memory for h.
In this example constructor call automatically because we created object h of class Human.
We use following single line code for creating object of a class,
which is simple form of above two line code.

Human h=new Human();






2 comments:

  1. hi om
    please tell me after learn java what's scop. i mean what am i able to do.

    ReplyDelete
  2. Java is not only for learning like any subject. Necessity is to be expert in java. i.e if you will be expert with concepts also with vast practical knowledge also then you can develop any application and you can get job according to your profile , software engineer, software developer, programmer....

    ReplyDelete