Java Program to Implement Constructor

Aim:

To write a Java program to implement constructor

1) A constructor with no parameters:

Program:

class A
{
int l,b;
A()
{
}
l=10;
b=20;
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area();
System.out.println("The area is: "+r);
}
}

Output:

The area is:200

2) A constructor with parameters:

Program:

class A
{
int l,b;
A(int u,int v)
{
l=u;
b=v;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(10,20);
int r=a1.area();
System.out.println("The area is: "+r);
}
}

Output:

The area is:200

Leave a Comment