Saturday, August 27, 2011

Java constructor example

Before going to the constructor example just take a look what is it actually?
Basically java support a special type of method called constructor which initialize itself when object is first created.
Constructor method has the same name as the class name and it don't have any return type not even "void".
In bellow example "ConstructorClass(int a,int b)" is a constructor method and it is initialized when object is created like our example as,
ConstructorClass ConstructorClassObject = new ConstructorClass(a,b);
********************************************************
//ConstructorClass.java
public class ConstructorClass
{
int l,w;
ConstructorClass(int a,int b) //constructor method
{
l=a;
w=b;
}
public void area()
{
System.out.println("area of "+l+" unit length and "+w+" unit width = "+(l*w)+" sq.unit");
}
}

//MainClass.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainClass
{
public static void main(String args[]) throws IOException
{

int a,b;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter length:");
a=Integer.valueOf(br.readLine()).intValue();

System.out.println("Enter width:");
b=Integer.valueOf(br.readLine()).intValue();

ConstructorClass ConstructorClassObject = new ConstructorClass(a,b);
ConstructorClassObject.area();
}
}



Output=>
Enter length:
5
Enter width:
4
area of 5 unit length and 4 unit width = 20 sq.unit

No comments:

Post a Comment