USE CONSTRUCTORS IN JAVA

WHAT IS CONSTRUCTORS?

A constructors initializes an object immediately upon  creation . It has the same name  as the class in which it resides and is syntactically similar to a method .Once defined, the constructor is automatically called immediately after the  object is created,before the new operator completes. Constructors look a Little strange because they have no return type,not even void.This is because the implicit return type of a class’ constructor is the class type itself. It is the constructors’s job to initialize the internal state of an object so that the code creating an instance will have a fully initialized ,usable object immediately.

In Java, some of the differences between other methods and constructors are:

  • Constructors never have an explicit return type.
  • Constructors cannot be directly invoked (the keyword “new” must be used).
  • Constructors cannot be synchronized, final, abstract, native, or static.

WHAT IS THIS KEY?

The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword.

for example :-

this.a=a,this.b=b

Example:-

/* Here , Demo uses a constructor to initialize the variable */

public class demo

{
int a,b;

/*This is the constructor for Demo*/
public demo(int a, int b)
{

this.a=a;
this.b=b;
}

/*compute the return addition , subtraction ,multiplication, division*/

public int add()
{
int c=a+b;
return c;

}
public int sub()
{
int c=a-b;
return c;
}
public int mul()
{
int c=a*b;
return c;
}
public float div()
{
int c=a/b;
return c;
}

public static void main(String[] args)
{

/* declare , allocate ,and initialize Demo object*/
demo d= new demo(23,5 );
System.out.println(“Addition=” +d.add());
System.out.println(“Substration=” +d.sub());
System.out.println(“Multiplication=” +d.mul());
System.out.println(“Division=” +d.div());
}

}

 

Output is give below:-

Addition=28
Substration=18
Multiplication=115
Division=4.0

 

Advertisements

About pinku12

HIMANSHU SRIVASTAVA VARANASI
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s